(6) Semaphores, Condition Variables and Monitors Flashcards
What is a Semaphore?
An -integer- variable indicating the number of simultaneous users that can access a shared resource.
Can only be access via two indivisible (atomic) ops:
wait(): while(S<=0): //busy wait; S–;
signal(): S++;
What are the two types of Semaphore?
Counting semaphore - integer val over unrestricted domain.
Binary semaphore - integer val over 0 and 1 i.e same as a lock.
(Can implement a counting semaphore as a binary semaphore)
Explain how the bounded buffer problem is solved.
We have Producer, Buffer and Consumer actors. Multiple producers and consumers, one master buffer actor. Producers request and send data to the master, consumers indicate they are ready and the master then removes an item to send to consumer. Producer only sends data to buffer when requested by buffer consumer doesn’t have to wait while the buffer is empty as it just has to inform the buffer when it is ready.
What are some problems with semaphores and locks?
Easy to make mistakes
- essentially shared global variables which can be accessed from anywhere (bad engineering)
- No connection between synchronization variable and the data controlled by it
- No control over their use/guarantee of proper usage, e.g with a Semaphore will there ever be a V()? Or with locks did you lock when necessary/unlock at the right time/at all?
What is a monitor?
A class in which every method automatically acquires a lock on entry and releases on exit. Holds shared data structures, procedures and synchronization inside it. Processes attempting to access the data in it have to go through the procedures in the monitor to access the data. Only one process is allowed in at a time. More restrictive than semaphores but easier to use mostly.
How do monitors get around the bounded buffer scenario?
Monitors require condition variables.
Ops on condition variables:
-wait(c)
release lock, wait for signal condition. meaning there is a wait queue.
-signal(c)
‘Hoare’ monitor - wake up at most one waiting thread. If no waiting thread then signal is lost - different from semaphores as no history.
-broadcast(c)
wake all waiting threads.