Presentation is loading. Please wait.

Presentation is loading. Please wait.

Synchronization, part 3 Monitors, classical sync. problems

Similar presentations


Presentation on theme: "Synchronization, part 3 Monitors, classical sync. problems"— Presentation transcript:

1 Synchronization, part 3 Monitors, classical sync. problems
Operating Systems Synchronization, part 3 Monitors, classical sync. problems

2 Monitor Monitor – a synchronization primitive
A monitor is a collection of procedures, variables and data structures, grouped together Mutual Exclusion – only one process can be active within a monitor at any given time Usually a programming language construct! The compiler of the language will know that monitors procedures are different than other procedures, and will treat them differently. That means that the compiler is in charge of the mutual exclusion implementation

3 Condition variables A way for processes to block when they can’t continue Despite its name, it is used to indicate an event and not as a regular valued variable. A CV is not a counter! Two operations: wait, signal Wait: causes the process to block, and allows entry of other threads to the monitor Signal: More than just one alternative: Hoare type monitors: The signaler yields the monitor to the released thread. Signal will be the last operation within the monitor, which wakes up waiting processes (waiting on the same variable). This is not true for Java. Mesa type monitors: The signaling process is allowed to continue Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods. The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

4 The Sleeping Barber Write a solution to the sleeping barber problem using monitors and condition variables The sleeping barber: The barber cuts peoples hair in his shop, which has 2 doors – entrance and exit. When people are in his shop, he gives them a hair cut, one at a time. When none are in his shop, he sleeps on his chair. When a customer arrives and finds the barber sleeping, he awakens him and sits in the barber’s chair to receive his haircut. After the cut is done, the barber sees the customer out through the exit door. If the barber is busy when a customer arrives, the customer waits in one of the chairs in the shop. If all are occupied, he goes away. After serving a customer the barber looks to see if any are waiting and if so proceeds to serve one of them. Otherwise, he sleeps again in his chair.

5 The Sleeping Barber barbershop: monitor
waiting : integer := 0; % customers waiting for haircut customers : condition; % used by barber, wait for a customer barber : condition; % used by customer, wait for barber procedure seek-customer( ) % called by the barber begin if waiting==0 then WAIT (customers); % sleeps if no customers waiting = waiting-1; % one less customer waiting cut-hair(); SIGNAL (barber); % free a waiting customer end seek-customer;

6 The Sleeping Barber procedure get-haircut( ) % called by a customer
begin % is there a free chair to sit and wait? % if no free chairs just go away if waiting < chairs then { waiting = waiting+1; % one more customer waiting SIGNAL (customers) % if the barber is asleep WAIT (barber); % wait for turn with the barber } end get-haircut; end barbershop; % End of monitor

7 Producer Consumers with Monitor
Monitor ProducerConsumer 1. condition full, empty 2. integer count initially 0 3. procedure insert(item: integer) 4. begin 5. if count=N then wait(full) 6. insert_item(item) 7. count=count+1 8. signal(empty) 9. end 10. procedure remove: integer 11. begin 12. if count=0 then wait(empty) 13. remove=remove_item() 14. count=count signal(full) 16. end end Monitor

8 Producer Consumers with Monitor
Monitor ProducerConsumer 1. condition full, empty 2. integer count initially 0 3. procedure insert(item: integer) 4. begin 5. if count=N then wait(full) 6. insert_item(item) 7. count=count+1 8. signal(empty) 9. end 10. procedure remove: integer 11. begin 12. if count=0 then wait(empty) 13. remove=remove_item() 14. count=count signal(full) 16. end end Monitor Will it work with Mesa type monitor? What about Hoare?

9 Java and monitors – Exercise
Write a code snippet in Java which will enforce a FIFO waking order (i.e., create a class in Java that will allow a programmer fair synchronization)

10 Spurious wakeups On some threading API’s (e.g., for linux and windows) monitors and conditional variables are vulnerable to spurious wakeups. Spurious wakeup describes a complication in the use of condition variables in which a thread might be awoken from its waiting state even though no thread signaled the condition variable. Since Java uses the native threads implementation (native for the OS which is running the JVM) one must handle spurious wakeups. For correctness it is necessary, then, to verify that the condition is indeed true after the thread has finished waiting and continue waiting otherwise.

11 Java and monitors – Solution
class SafeMonitor { boolean released = false; // this flag avoids race!!! synchronized void await() throws InterruptedException { while (! released) { wait(); } } synchronized void signal(){ if (! released){ released = true; notify(); } } }

12 Java and monitors – Solution
class CriticalSection { private List<SafeMonitor> waiting; private boolean busy; public CriticalSection() { waiting = new LinkedList<>(); busy = false; } public synchronized void enter() { if (! busy) { busy = true; } else { SafeMonitor myLock = new SafeMonitor(); waiting.add(myLock); myLock.await(); } } public synchronized void leave() { if (!waiting.isEmpty()) { waiting.remove().signal(); } else { busy = false; }

13 Java and monitors – Solution
class CriticalSection { private List<SimpleMonitor> waiting; private boolean busy; public CriticalSection() { waiting = new LinkedList<>(); busy = false; } public synchronized void enter() { if (! busy) { busy = true; } else { SimpleMonitor myLock = new SimpleMonitor(); waiting.add(myLock); myLock.doWait(); } } public synchronized void leave() { if (!waiting.isEmpty()) { waiting.remove().doNotify(); } else { busy = false; } Does this code guarantee a FIFO waking order which is equivalent to the order in which threads reached the critical section entrance? What happens when multiple threads attempt to enter at the same time?

14 The one-way tunnel problem
Allows any number of processes in the same direction If there is traffic in the opposite direction – have to wait A special case of readers/writers

15 The one way tunnel (exam 2004)
The one way tunnel solution: int count[2]; Semaphore busy=1; Semaphore waiting[2]={1,1}; void arrive(int direction){ down(&waiting[direction]); count[direction]+=1; if (count[direction]==1){ down(&busy); } up(&waiting[direction]); void leave(int direction){ down(&waiting[direction]); count[direction]-=1; if (count[direction]==0){ up(&busy); } up(&waiting[direction]);

16 The one way tunnel (exam 2004)
Add changes to the one way tunnel solution so that there will be no starvation. If vehicles are present on both “0” and “1” they will take alternate turns in entering the tunnel. When there are vehicles coming from only one direction, they can pass through with no limitations. Notes: you may only use integers and binary semaphores (can assume fairness).

17 The one way tunnel (exam 2004)
The one way tunnel solution: int count[2]; Semaphore busy=1; Semaphore waiting[2]={1,1}; Semaphore waiting2[2]={1,1}; void arrive(int direction){ down(&waiting2[direction]); down(&waiting[direction]); count[direction]+=1; if (count[direction]==1){ down(&waiting2[1-direction]); down(&busy); up(&waiting2[1-direction]); } up(&waiting[direction]); up(&waiting2[direction]); void leave(int direction){ down(&waiting[direction]); count[direction]-=1; if (count[direction]==0){ up(&busy); } up(&waiting[direction]);

18 Message passing Used on distributed systems (when there is no shared memory). Uses send(), and receive() system calls. Introduces a new set of problems, such as acknowledgments, sequencing, addressing, authentication, etc’…

19 Reader/Writer problem with MP
Write a solution to the reader/writer problem using Message Passing. Assume the following: Three groups of processes: readers, writer, manager. Multiple readers may access the DB simultaneously. A writer needs exclusive access to the DB. Readers have preference.

20 Reader/Writer problem with MP
Reader: while (true){ SEND (manager, start_read); RECEIVE (manager, msg); % wait for confirmation read_db(); SEND (manager, end_read); use_data(); } Writer: while (true){ generate_data(); SEND (manager, start_write); RECEIVE (manager, msg); % wait for confirmation write_to_db(); SEND (manager, end_write);

21 Reader/Writer problem with MP
Manager: int readers_count=0; % number of readers accessing DB boolean writing=false; % writing flag Message msg; Queue readQ, writeQ; % Queues for waiting readers and writers ProcessID src; % pid while (true){ src = RECEIVE(msg); switch msg.type{ case (start_read): if (not writing){ send(src, ok); readers_count++; } else readQ.add(src);

22 Reader/Writer problem with MP
case (end_read): readers_count--; if (readers_count==0 && not writeQ.empty){ src=writeQ.remove; SEND (src, ok); writing = true; } case (start_write): if (readers_count==0 && not writing){ SEND (src, ok); writing = true; } else writeQ.add(src);

23 Reader/Writer problem with MP
case (end_write): writing = false; if (readQ.empty && not writeQ.empty){ src = writeQ.remove; SEND(src, ok); writing = true; } else { while (not readQ.empty){ src = readQ.remove; send(src, ok); readers_count++; } } } % switch } % while


Download ppt "Synchronization, part 3 Monitors, classical sync. problems"

Similar presentations


Ads by Google