COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

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.
Ken Birman 1. Refresher: Dekers Algorithm Assumes two threads, numbered 0 and 1 CSEnter(int i) { int J = i^1; inside[i] = true; turn = J; while(inside[J]
1 Condition Synchronization. 2 Synchronization Now that you have seen locks, is that all there is? No, but what is the “right” way to build a parallel.
1 Semaphores and Monitors: High-level Synchronization Constructs.
COSC 3407: Operating Systems Lecture 8: Semaphores, Monitors and Condition Variables.
CS162 Operating Systems and Systems Programming Lecture 9 Deadlock September 28, 2005 Prof. John Kubiatowicz
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization February 13, 2006 Prof. Anthony D. Joseph.
CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization September 26, 2005 Prof. John Kubiatowicz.
CS194-3/CS16x Introduction to Systems Lecture 7 Monitors, Readers/Writers problem, Language support for concurrency control, Relational model September.
CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization September 23, 2009 Prof. John Kubiatowicz.
Monitors CSCI 444/544 Operating Systems Fall 2008.
CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization September 25, 2006 Prof. John Kubiatowicz.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Monitor Solutions to Classical Problems. 2 Announcements CS 415 Projects graded. –Mean 80.7, High 90 out of 90 CS 414 Homework due Monday.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
CS Advanced Operating Systems Structures and Implementation Lecture 8 Synchronization Continued February 25 th, 2013 Prof. John Kubiatowicz
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Atomic Operations David Monismith cs550 Operating Systems.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Processes and Threads-V Concurrency and Synchronization.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
CS162 Operating Systems and Systems Programming Lecture 5 Semaphores, Conditional Variables February 2, 2011 Ion Stoica
ICS 313: Programming Language Theory Chapter 13: Concurrency.
CS162 Operating Systems and Systems Programming Lecture 7 Readers-Writers Language Support for Synchronization February 13, 2008 Prof. Anthony D. Joseph.
1 Interprocess Communication (IPC) - Outline Problem: Race condition Solution: Mutual exclusion –Disabling interrupts; –Lock variables; –Strict alternation.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
CS 162 Discussion Section Week 4. Administrivia Design reviews Friday, Monday and Tuesday – Every member must attend – Will test that every member understands.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
1 Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois.
13/03/07Week 21 CENG334 Introduction to Operating Systems Erol Sahin Dept of Computer Eng. Middle East Technical University Ankara, TURKEY URL:
Problems with Semaphores Used for 2 independent purposes –Mutual exclusion –Condition synchronization Hard to get right –Small mistake easily leads to.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
CSE 153 Design of Operating Systems Winter 2015 Midterm Review.
CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization Friday 11, 2010 Ion Stoica
1 Previous Lecture Overview  semaphores provide the first high-level synchronization abstraction that is possible to implement efficiently in OS. This.
Dining Philosophers & Monitors Questions answered in this lecture: How to synchronize dining philosophers? What are monitors and condition variables? What.
Implementing Lock. From the Previous Lecture  The “too much milk” example shows that writing concurrent programs directly with load and store instructions.
3/17/2016cse synchronization-p2 © Perkins, DW Johnson and University of Washington1 Synchronization Part 2 CSE 410, Spring 2008 Computer.
Implementing Mutual Exclusion Andy Wang Operating Systems COP 4610 / CGS 5765.
CS162 Section 2. True/False A thread needs to own a semaphore, meaning the thread has called semaphore.P(), before it can call semaphore.V() False: Any.
CS162 Operating Systems and Systems Programming Lecture 9 Synchronization, Readers/Writers example, Scheduling September 26th, 2016 Prof. Anthony D.
CS703 - Advanced Operating Systems
2 July 2015 Charles Reiss
CS703 – Advanced Operating Systems
Monitors, Condition Variables, and Readers-Writers
Processes and Monitors in Mesa (Lecture 6, cs262a)
CSCI 511 Operating Systems Chapter 5 (Part C) Monitor
February 7, 2011 Ion Stoica CS162 Operating Systems and Systems Programming Lecture 6 Semaphores, Conditional Variables,
Introduction to Operating Systems
September 19, 2012 Ion Stoica CS162 Operating Systems and Systems Programming Lecture 7 Semaphores, Conditional Variables,
Anthony D. Joseph and Ion Stoica
Anthony D. Joseph and Ion Stoica
Threading And Parallel Programming Constructs
CS703 - Advanced Operating Systems
Anthony D. Joseph and Ion Stoica
Implementing Mutual Exclusion
Implementing Mutual Exclusion
September 12, 2012 Ion Stoica CS162 Operating Systems and Systems Programming Lecture 5 Semaphores, Conditional Variables.
Chapter 6: Synchronization Tools
CSE 153 Design of Operating Systems Winter 2019
Chapter 7: Synchronization Examples
Don Porter Portions courtesy Emmett Witchel
Review The Critical Section problem Peterson’s Algorithm
Presentation transcript:

COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization

This lecture… u Review definition of monitors and condition variables u Illustrate use of monitors and condition variables by solving readers-writers problem u Language support can make thread programming easier. u Threads are a fundamental OS abstraction, but be careful about how you use them. u Summarize concurrency section

Readers/Writers u Shared database (for example, bank balances, or airline seats) u Two classes of users: – Readers – never modify database – Writers – read and modify database u Using a single lock on the database would be overly restrictive. Want: – many readers at same time – only one writer at same time

Readers/Writers u Constraints: 1.Readers can access database when no writers (Condition okToRead) 2.Writers can access database when no readers or writers (Condition okToWrite) 3.Only one thread manipulates state variables at a time.

Readers/Writers u Solution – Basic structure of solution Reader wait until no writers access database check out – wake up waiting writer Writer wait until no readers or writers access database check out – wake up waiting readers or writer State variables: # of active readers – AR = 0 # of active writers – AW = 0 # of waiting readers – WR = 0 # of waiting writers – WW = 0 Condition okToRead = NIL Condition okToWrite = NIL Lock lock = FREE

Readers/Writers u Code: Reader() { // first check self into system lock.Acquire(); while ((AW + WW) > 0) { // check if safe to read if any writers, wait WR++; okToRead.Wait(&lock); WR--; } AR++; lock.Release(); Access DB // check self out of system lock.Acquire(); AR--; if (AR == 0 && WW > 0) //if no other readers still active, wake up writer okToWrite.Signal(&lock); lock.Release(); }

Readers/Writers Writer() { // symmetrical // check in lock.Acquire(); while ((AW + AR) > 0) { // check if safe to write if any readers or writers, wait WW++; okToWrite.Wait(&lock); WW--; } AW++; lock.Release(); Access DB // check out lock.Acquire(); AW--; if (WW > 0) // give priority to other writers okToWrite.Signal(&lock); else if (WR > 0) okToRead.Broadcast(&lock); lock.Release(); }

Readers/Writers u Questions: 1.Can readers starve? 2.Why does checkRead need a while?

Modified Reader Reader() { // first check self into system lock.Acquire(); while ((AW + WW) > 0) { // check if safe to read if any writers, wait WR++; ok.Wait(&lock); WR--; } AR++; lock.Release(); Access DB // check self out of system lock.Acquire(); AR--; ok.broadcast(&lock); lock.Release(); }

Modified Writer Writer() { // symmetrical // check in lock.Acquire(); while ((AW + AR) > 0) { // check if safe to write if any readers or writers, wait WW++; ok.Wait(&lock); WW--; } AW++; lock.Release(); Access DB // check out lock.Acquire(); AW--; if (WW > 0) or (WR > 0) ok.Broadcast(&lock); lock.Release(); }

Semaphores Vs. Monitors u Illustrate the differences by considering: can we build monitors out of semaphores? u After all, semaphores provide atomic operations and queuing. u Does this work? u Condition variables only work inside of a lock. u If you try to use semaphores inside of a lock, you have to watch for deadlock. Wait() { semaphore->P(); } Signal() { semaphore->V(); }

Semaphores Vs. Monitors u Does this work? Wait(Lock *lock) { lock->Release(); semaphore->P(); lock->Acquire(); } Signal() { semaphore->V(); }

Semaphores Vs. Monitors u Condition variables have no history, but semaphores do have history. u What if thread signals and no one is waiting? – No op. u What if thread later waits? – Thread waits. u What if thread V’s and no one is waiting? – Increment. u What if thread later does P? – Decrement and continue.

Semaphores Vs. Monitors u In other words, P + V are commutative – result is the same no matter what order they occur. u Condition variables are not commutative. u That’s why they must be in a critical section – need to access state variables to do their job. u Does this fix the problem? u For one, it is not legal to look at contents of semaphore queue. u But, there is also a race condition – signaler can slip in after lock is released, and before wait. u Then waiter never wakes up! u Program needs to release lock and go to sleep atomically. u Is it possible to implement condition variables using semaphores? See book! (complex solution for Hoare scheduling) Signal() { if semaphore queue is not empty semaphore->V(); }

Summary of Monitors u Monitors represent the logic of the program – wait if necessary, signal if change something so waiter might need to wake up. lock while (need to wait) { wait(); } unlock do something so no need to wait lock signal(); unlock

Language support for thread synchronization u The problem with requiring the programmer to specify both lock acquire and release statements is that he might forget to put a release everywhere it is needed. u Languages like C – This is not too bad in a language like C: just make sure you know all the code paths out of a critical section: – Watch out for setjmp/longjmp! (Might happen in called procedure) int Rtn() { lock.acquire(); … if (exception) { lock.release(); return errReturnCode; } … lock.release(); return OK; } Proc E calls longjmp Proc D Proc C lock.acquire Proc B calls setjmp Proc A

Language support for thread synchronization u Languages like C++ – Languages that support exceptions – like C++ – are more problematic: – Notice that an exception in DoFoo() will exit without releasing the lock void Rtn() { lock.acquire(); … DoFoo(); … lock.release(); } void DoFoo() { … if (exception) throw errException; … }

Languages like C++ u Rtn() needs to catch the exception, release the lock, and then re-throw the exception: void Rtn() { lock.acquire(); try { … DoFoo(); … } catch (…) { // C++ syntax for catching any exception. lock.release(); throw; // C++ syntax for re-throwing an exception. } lock.release(); }

Language support for thread synchronization u Java – Java has explicit support for threads and thread synchronization. u Bank account example: class Account { private int balance; // object constructor public Account (int initialBalance) { balance = initialBalance; } public synchronized int getBalance() { return balance; } public synchronized void deposit(int amount) { balance += amount; }

Java u Each Account object has an associated lock, which gets automatically acquired and released on entry and exit from each synchronized method. u Java also has synchronized statements: u Every Java object has an associated lock. u Any Java object can be used to control access to a synchronized block of code. synchronized (object) { … }

Java u The synchronizing object’s lock is acquired on entry and released on exit, even if exit is by means of a thrown exception: synchronized (object) { … DoFoo(); … } void DoFoo() { … throw errException; … }

Java u How to wait in a synchronized method or code block: – void wait(long timeout); – void wait(long timeout, int nanoseconds); – void wait(); u How to signal in a synchronized method or code block: – void notify(); wakes up the longest waiting waiter – void notifyAll(); like broadcast,wakes up all waiters

Java u Notes: – Only one condition variable per lock. – Condition variables can wait for a bounded length of time. This is useful for handling exception cases where something has failed. For example: – One reason why all Java Virtual Machines are not equivalent: » Different thread scheduling policies. » The language specification does not stipulate whether preemptive scheduling is required or what granularity of time slice should be used if preemptive scheduling is provided. t1 = time.now(); while (!ATMRequest()) { wait(LONG_TIME); t2 = time.now(); if (t2 – t1 > LONG_TIME) CheckIfMachineBroken(); }