Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ref: William Stallings,Galvin, Naresh Chauhan G.Anuradha

Similar presentations


Presentation on theme: "Ref: William Stallings,Galvin, Naresh Chauhan G.Anuradha"— Presentation transcript:

1 Ref: William Stallings,Galvin, Naresh Chauhan G.Anuradha
Semaphores Ref: William Stallings,Galvin, Naresh Chauhan G.Anuradha

2 What is a semaphore? Popular tool for process synchronization
Used to protect any resource such as global shared memory that needs to be accessed and updated by many processes Analogy- allotment of seminar room for various activites of college. 9/17/2018

3 Principle of a Semaphore
For signaling semaphores are used For sending a signal semSignal (s) is used For receiving a signal semWait(s) is used First defined by Dijkstra Semaphore is a variable A semaphore may be initialized to a nonnegative integer value. The semWait operation decrements the semaphore value. The semSignal operation increments the semaphore value.

4 wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++;
9/17/2018

5 Definition of semaphore

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41 Types of Semaphores Binary semaphore:-takes value 0 and 1-used for resource having a single instance Counting Semphore:- when there are more than one process. Mutex:-similar to binary semaphore but the key difference is that the mutex is locked and unlocked by the same process

42 Classical Synchronization problems
Producer consumer problem Reader-writer problem Barber shop Dining philosopher

43 I. Producer-Consumer Imagine a chef cooking items
and putting them onto a conveyor belt 43 43

44 Producer-Consumer Imagine a chef cooking items
and putting them onto a conveyor belt Now imagine many such chefs! 44

45 Producer-Consumer Imagine a chef cooking items
and putting them onto a conveyor belt Now imagine many such chefs! 45

46 Producer-Consumer Imagine a chef cooking items
and putting them onto a conveyor belt Now imagine many such chefs! Now imagine a customer picking items off the conveyor belt 46

47 Producer-Consumer Imagine a chef cooking items
and putting them onto a conveyor belt Now imagine many such chefs! Now imagine many such customers picking items off the conveyor belt! 47

48 Producer-Consumer Imagine a chef cooking items
and putting them onto a conveyor belt Now imagine many such chefs! Now imagine many such customers picking items off the conveyor belt! 48

49 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 49

50 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 50

51 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 51

52 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 52

53 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 53

54 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 54

55 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 55

56 Producer-Consumer Chef = Producer Customer = Consumer
BUFFER FULL: Producer must be blocked! insertPtr removePtr 56

57 Producer-Consumer Chef = Producer Customer = Consumer insertPtr
removePtr 57

58 Producer-Consumer Chef = Producer Customer = Consumer removePtr
insertPtr 58

59 Producer-Consumer Chef = Producer Customer = Consumer removePtr
insertPtr 59

60 Producer-Consumer Chef = Producer Customer = Consumer removePtr
insertPtr 60

61 Producer-Consumer Chef = Producer Customer = Consumer removePtr
insertPtr 61

62 Producer-Consumer Chef = Producer Customer = Consumer removePtr
insertPtr 62

63 Producer-Consumer Chef = Producer Customer = Consumer removePtr
insertPtr 63

64 Producer-Consumer Chef = Producer Customer = Consumer
BUFFER EMPTY: Consumer must be blocked! removePtr insertPtr 64

65 Producer Consumer problem
Infinite buffer

66 Solution of Producer consumer using Semaphores
Examples Compiler is a producer producing object code Assembler is a consumer that takes object code Printing a file is a producer process Printing file on the printer is a consumer process 9/17/2018

67 Requirements to solve producer consumer problem
Producer should not produce an item when buffer is full Consumer should not consume when buffer is empty Producer and consumer should not try to access and update the buffer at the same time Producer is full and item is produced then producer should be blocked If consumer is ready and buffer is empty then consumer should be blocked When a consumer process consumes an item, that is, a slot in the buffer is created the blocked producer must be signaled about it. When a producer process produces an item in the empty buffer, blocked consumer process must be signaled about it. 9/17/2018

68 3 semaphores are used in the solution
Producer Consumer problem can be solved by placing a semaphore on the buffer. Two more semaphores are taken which will count the number of empty slots and full slots in the buffer. 3 semaphores are used in the solution empty semaphore initialized to n where n is the number of empty slots in the buffer full semaphore initialized to zero buffer-access semaphore initialized to one

69 Algorithms for producer-consumer problem’s solution with Semaphore

70 The producer after producing the item waits on the empty semaphore to check for an empty slot
Then it waits for the Buffer-access semaphore to check whether any other process is accessing it After getting permission it stores After storing it signals the buffer_access so that any other process in wait can access the buffer.

71 What is a reader writer problem?
Y N Where was it used?

72 Reader-Writer problem using Semaphore
Case 1: Readers have the priority One reader process is inside the critical section and multiple writer processes arrive, then they must wait on the semaphore. One writer process is inside the critical section and multiple reader processes arrive, then they must wait on the semaphore. One reader process is inside the critical section and multiple reader processes arrive, then they will not wait on the semaphore. One writer process is inside the critical section and multiple writer processes arrive, then they must wait on the semaphore.

73 Reader-Writer problem using Semaphore
ReadCount : integer variable as counter for reader processes; initialized as 0. Sem_ReadCount: semaphore for ReadCount; initialized as 1 Sem_ReadWrite: semaphore for mutual exclusion between reader and writer processes; initialized as 1

74 Algorithms for reader-writer problem’s solution with semaphore: Readers have priority

75 Reader-Writer problem using Semaphore
Case 2: Writers have the priority Solution must be designed such that long queue of readers are not allowed where writers are waiting. For this another semaphore Sem_restrict is used which will restrict the readers from entering the queue. If no writer is accessing the CS and new writer arrives then it will also wait on Sem_restrict so that readers do not monopolize and writers can start

76 Scenarios in writers having priority
If no writer is accessing the CS and new writer arrives then it will also wait on Sem_restrict so that readers do not monopolize and writers can start. Once a writer enters the Cs and there are writers and readers waiting then only writers will be allowed to access. After all writers finish their work, if a reader appears then the reader will be given access first.

77 Algorithm for writers having priority
Reader() { While(true){ Wait(Sem_readerWait); Wait(Sem_restrict); Wait(Sem_readcount) readcount++ if(readcount==1) wait(sem_readwrite); signal(sem_readcount); signal(sem_restrict); signal(sem_readerWait); Perform the read operation wait(sem_readCount); readcount--; if(readcount==0) signal(sem_readwrite) signal(sem_readcount) }} Writer() { While(true){ Wait(Sem_writecount) writecount++ if(writecount==1) wait(sem_restrict); signal(sem_writecount); wait(sem_readwrite); Perform the write operation signal(sem_readwrite) wait(sem_writeCount); writecount--; if(writecount==0) signal(sem_restrict) signal(sem_writecount) }}

78 Case 3: No priority Reader() { While(true){ Wait(sem_count)
If (writecount>0) OR readcount = = 0) Signal(sem_count); Wait(sem_readcount); Wait(sem_count); } ReadCount--; If(readcount==0) signal(sem_readwrite) signal(sem_count); }} Writer { while(true){ wait(sem_count); writecount++; signla(Sem_count); wait(sem_readwrite); Perform the write operation writecount--; signal(sem_count); signal(sem_readwrite); }}

79 Barbershop Problem 3 barbers, each with a barber chair
Haircuts may take varying amounts of time Sofa can hold 4 customers, max of 20 in shop Customers wait outside if necessary When a chair is empty: Customer sitting longest on sofa is served Customer standing the longest sits down After haircut, go to cashier for payment Only one cash register Algorithm has a separate cashier, but often barbers also take payment This is also a critical section

80 II. Reader-Writer Problem
A reader: read data A writer: write data Rules: Multiple readers may read the data simultaneously Only one writer can write the data at any time A reader and a writer cannot access data simultaneously Locking table: whether any two can be in the critical section simultaneously Reader Writer OK No 80

81 III. Dining Philosophers: an intellectual game
1 81

82 Problem Statement Five philosophers eat then think forever
They never sleep nor relieve themselves! They do not behave altruistically They eat at a communal table It has a single bowl of tangled spaghetti Five plates each with a single fork to the left of their plate To eat a philosopher must have two forks, their own and that of their neighbour’s to the right If a philosopher is unable to eat they resume thinking

83 Ramifications Deadlock Starvation
All philosophers decide to eat at same time They all pick up one fork None of them can eat hence the system comes to a halt Starvation Some philosophers think for such a short time and contrive to put their forks down in such a way that no other philosophers have the opportunity to pick up the two forks they require to eat

84 Deadlock - Pictorially

85 Starvation - Pictorially

86 Naïve Solution Unconstrained picking up and putting down of forks causes problems So put down in the reverse order of picking up Manage the entry and exit of philosophers to the table by means of a Butler process that entry and exit is orderly Each fork is a process Accessed either from left or right hand

87 Deadlocks Each philosopher has their left fork BUT
Cannot get a right fork Butler did nothing Needs to control access to table so that there is always one empty seat Ensures one philosopher can eat

88 Butler Controls No more than 4 philosopher can sit at the table (enter) Once 4 philosophers seated then Butler only lets people exit (get down) from the table

89 Problems with Semaphores
Incorrect usage of semaphores leads to timing errors Timing errors occur only if some particular execution sequence takes place.(rare) InCorrect use of semaphore operations signal (mutex) …. wait (mutex) (multiple CS) wait (mutex) … wait (mutex) (deadlock) Omitting of wait (mutex) or signal (mutex) (or both)

90 Monitors A high-level abstraction (ADT) that provides a convenient and effective mechanism for process synchronization Only one process may be active within the monitor at a time Has one or more procedure, initialization sequence, local data Local data variables are accessible only by the monitor’s procedures and not by any external procedure monitor monitor-name { // shared variable declarations procedure P1 (…) { …. } procedure Pn (…) {……} Initialization code ( ….) { … } }

91 Schematic view of a Monitor
91

92 Condition Variables Synchronization is supported by the use of condition variables that are contained and accessible only within the monitor condition x, y; Two operations on a condition variable: x.wait () – Suspends execution of the calling process on condition x. monitor is available for use by another process x.signal () – resumes execution of some process suspended after a wait on the same condition. one of processes (if any) that is invoked 92

93 Monitor with Condition Variables
93

94 Monitors for Producer consumer problem
Monitor module used to control the buffer to store and retrieve characters. Condition variables Not full :- TRUE then there is room to add atleast one character to the buffer Not empty :- TRUE then there is atleast one character in the buffer 94

95

96 Monitors for Producer consumer Bounded Buffer problem

97 Solution to Dining Philosophers
monitor DP { enum { THINKING; HUNGRY, EATING) state [5] ; condition self [5];’/* hungry but is unable to obtain forks*/ /* A philosopher can set state[i]=eating only if state (i+4)%5 and (i+1)%5 are not eating */ void pickup (int i) { state[i] = HUNGRY; test(i); if (state[i] != EATING) self [i].wait; } void putdown (int i) { state[i] = THINKING; // test left and right neighbors test((i + 4) % 5); test((i + 1) % 5);

98 Solution to Dining Philosophers (cont)
void test (int i) { if ( (state[(i + 4) % 5] != EATING) && (state[i] == HUNGRY) && (state[(i + 1) % 5] != EATING) ) { state[i] = EATING ; self[i].signal () ; } initialization_code() { for (int i = 0; i < 5; i++) state[i] = THINKING; 98

99 Solution to Dining Philosophers (cont)
Each philosopher I invokes the operations pickup() and putdown() in the following sequence: dp.pickup (i) EAT dp.putdown (i) No two neighbours eat simultaneously and no deadlocks will occur. But a philosopher can starve to death………………………… 99

100 Synchronization Hardware
One simple solution to the critical section problem is a lock

101 Hardware solutions In a uniprocessor environment, the interrupts could be prevented from occurring while a shared variable was modified(nonpreemptive) TestAndSet() and Swap() instructions are used in multiprocessor environment

102 Definition of the TestAndSet()
The semantics of test-and-set are: ◆ Record the old value and ◆ Set the value to indicate available and ◆ Return the old value

103

104

105

106

107

108

109 Compare and Swap

110

111 Compare and swap global variable lock is declared and initialized to 0. the first process that invokes compare_and_swap sets lock to 1 subsequent calls will not succeed when a process exits CS sets lock to 0 so that other process can enter

112

113 Data Structures are first initialized to false
Pi can enter CS only if waiting[i] and key are both false key becomes false only in test and set is false waiting[i] can become false only if another process leaves its critical section; only one waiting[i] is set to false maintaining the mutual exclusion requirement

114 University questions In a typical process state transition diagram. Clearly state under what condition the following state transition occur? running to ready running to waiting waiting to ready. Consider a system running 10 I/O bound tasks and 1 CPU bound task issues an I/O operation once for every millisecond of CPU computing and that each I/O operation takes 10 ms. context switch takes 0.1ms and all processes are long running tasks. what is the CPU utilization for RR scheduler when the quantum is 1ms the quantum is 10ms Suggest the implementation of binary semaphore that avoids the buzy waiting What is a thread? Explain ULT and KLT

115

116 What are preemptive and nonpreemptive algorithms
write short notes on race conditions


Download ppt "Ref: William Stallings,Galvin, Naresh Chauhan G.Anuradha"

Similar presentations


Ads by Google