Synchronization, part 3 Monitors, classical sync. problems

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

1 Interprocess Communication 1. Ways of passing information 2. Guarded critical activities (e.g. updating shared data) 3. Proper sequencing in case of.
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Ch 7 B.
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Chapter 6: Process Synchronization
1 Semaphores and Monitors CIS450 Winter 2003 Professor Jinhua Guo.
Classic Synchronization Problems
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization.
Avishai Wool lecture Introduction to Systems Programming Lecture 4 Inter-Process / Inter-Thread Communication.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
Review: Producer-Consumer using Semaphores #define N 100// number of slots in the buffer Semaphore mutex = 1;// controls access to critical region Semaphore.
02/17/2010CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
02/19/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
More Synchronisation Last time: bounded buffer, readers-writers, dining philosophers Today: sleeping barber, monitors.
Operating Systems CSE 411 CPU Management Oct Lecture 13 Instructor: Bhuvan Urgaonkar.
Semaphores. Readings r Silbershatz: Chapter 6 Mutual Exclusion in Critical Sections.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Outline Monitors Barrier synchronization The sleeping barber problem
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Classical problems.
6.3 Peterson’s Solution The two processes share two variables: Int turn; Boolean flag[2] The variable turn indicates whose turn it is to enter the critical.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization.
Synchronization, part 3 Monitors, classical sync. problems
1 Interprocess Communication (IPC) - Outline Problem: Race condition Solution: Mutual exclusion –Disabling interrupts; –Lock variables; –Strict alternation.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
1 Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois.
Operating Systems CSE 411 CPU Management Dec Lecture Instructor: Bhuvan Urgaonkar.
13/03/07Week 21 CENG334 Introduction to Operating Systems Erol Sahin Dept of Computer Eng. Middle East Technical University Ankara, TURKEY URL:
Concurrency in Shared Memory Systems Synchronization and Mutual Exclusion.
CS4315A. Berrached:CMS:UHD1 Process Synchronization Chapter 8.
Process Synchronization CS 360. Slide 2 CS 360, WSU Vancouver Process Synchronization Background The Critical-Section Problem Synchronization Hardware.
Homework-6 Questions : 2,10,15,22.
Chapter 6 Synchronization Dr. Yingwu Zhu. The Problem with Concurrent Execution Concurrent processes (& threads) often access shared data and resources.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
Synchronization, part 3 Monitors, classical sync. problems
Synchronization Semaphores
Interprocess Communication Race Conditions
Semaphore Synchronization tool that provides more sophisticated ways (than Mutex locks) for process to synchronize their activities. Semaphore S – integer.
Auburn University COMP 3500 Introduction to Operating Systems Synchronization: Part 4 Classical Synchronization Problems.
PARALLEL PROGRAM CHALLENGES
Background on the need for Synchronization
CIS Operating Systems Synchronization
Synchronization, part 3 Monitors, classical sync. problems
CS 3340 Windows Programming
Day 13 Concurrency.
Day 15 Concurrency.
Synchronization, part 3 Monitors, classical sync. problems
Lecture 13: Producer-Consumer and Semaphores
Chapter 5: Process Synchronization
Semaphore Originally called P() and V() wait (S) { while S <= 0
Process Synchronization
Synchronization, part 3 Monitors, classical sync. problems
Synchronization Hank Levy 1.
Critical section problem
Chapter 7: Synchronization Examples
CSE 451: Operating Systems Autumn Lecture 8 Semaphores and Monitors
CSE 451: Operating Systems Autumn Lecture 7 Semaphores and Monitors
Chapter 6 Synchronization Principles
Lecture 13: Producer-Consumer and Semaphores
Synchronization Hank Levy 1.
CSE 153 Design of Operating Systems Winter 2019
CS333 Intro to Operating Systems
“The Little Book on Semaphores” Allen B. Downey
Synchronization, Part 2 Semaphores
Synchronization, part 3 Monitors, classical sync. problems
Process/Thread Synchronization (Part 2)
Synchronization CSE 2431: Introduction to Operating Systems
Presentation transcript:

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

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

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 http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29 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.

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.

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;

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

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-1 15. signal(full) 16. end end Monitor

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-1 15. signal(full) 16. end end Monitor Will it work with Mesa type monitor? What about Hoare?

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)

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.

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(); } } }

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

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

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

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

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).

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

One way, convoy (midterm 2008) In the following question you must implement a solution to the convoy problem using only semaphores (and regular variables). In this problem, each thread represent a vehicle. The vehicles must go through a one way tunnel, but unlike the tunnel problem, here vehicles may only cross the tunnel in groups of exactly 5 (all in the same direction). A group of another 5 vehicles (from the same or opposite direction) may cross the tunnel again, only after the previous group of 5 vehicles comes out of it. The general code structure is as follows: Variable Declaration PrepareToCross(int direction) CROSS DoneWithCrossing(int direction)

One way, convoy (midterm 2008) Implement PrepareToCross() and DoneWithCrossing(). For your implementation you may only use semaphores (counting or binary) and regular variables. No busy-waiting is allowed. We say a thread is passing the tunnel if it completed its call to PrepareToCross and haven’t called DoneWithCrossing or if it is still in PrepareToCross but is no longer waiting on a semaphore, and when it will receive CPU time it may complete the procedure without waiting. Your implementation must satisfy the following conditions: Mutual Exclusion – threads from different direction may never be in the tunnel at the same time. Threads may only cross in groups of 5. When the first is leaving PrepareToCross, there are exactly 4 others which are passing the tunnel as well. Progress – Whenever there are 5 (or more) threads from the same direction waiting to cross the tunnel, then eventually, 5 will.

One way, convoy (midterm 2008) We will use the following: Counting Semaphore waitingToCross[]={5,5} Counting Semaphore barrier[]={0,0} Binary Semaphore busy=1 Binary Semaphore mutex=1 int waitingCount[]={0,0} int passed=0

One way, convoy (midterm 2008) PrepareToCross(int i){ down(&waitingToCross[i]); down(&mutex); waitingCount[i]++; If (waitingCount[i]<5){ up(&mutex); down(&barrier[i]); } else { waitingCount[i]=0; down(&busy); for (int k=0; k<4; k++) up(&barrier[i]); } up(&waitingToCross[i]); DoneWithCrossing(int i){ down(&mutex); passed++; if (passed==5){ passed=0; up(&busy); } up(&mutex);

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’…

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.

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);

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);

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);

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