Monitors and Semaphores. Annotated Condition Variable Example Condition *cv; Lock* cvMx; int waiter = 0; void await() { cvMx->Lock(); waiter = waiter.

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.
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Ch 7 B.
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
1 Semaphores and Monitors CIS450 Winter 2003 Professor Jinhua Guo.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Sleep/Wakeup and Condition Variables. Example: Await/Awake Consider a very simple use of sleep/wakeup to implement two new primitives: currentThread->Await()
1 Semaphores and Monitors: High-level Synchronization Constructs.
COSC 3407: Operating Systems Lecture 8: Semaphores, Monitors and Condition Variables.
02/19/2010CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
Language Support for Concurrency. 2 Common programming errors Process i P(S) CS P(S) Process j V(S) CS V(S) Process k P(S) CS.
5.6.2 Thread Synchronization with Semaphores Semaphores can be used to notify other threads that events have occurred –Producer-consumer relationship Producer.
Synchronization: Monitors Hank Levy. 6/21/20152 Synchronization with Semaphores Semaphores can be used to solve any of the traditional synchronization.
CS444/CS544 Operating Systems Synchronization 2/21/2007 Prof. Searleman
Monitors CSCI 444/544 Operating Systems Fall 2008.
Semaphores CSCI 444/544 Operating Systems Fall 2008.
02/25/2004CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
University of Pennsylvania 9/28/00CSE 3801 Concurrent Programming (Critical Regions, Monitors, and Threads) CSE 380 Lecture Note 6 Insup Lee.
02/19/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Discussion Week 3 TA: Kyle Dewey. Overview Concurrency overview Synchronization primitives Semaphores Locks Conditions Project #1.
Monitor  Giving credit where it is due:  The lecture notes are borrowed from Dr. I-Ling Yen at University of Texas at Dallas  I have modified them and.
CS510 Concurrent Systems Introduction to Concurrency.
Experience with Processes and Monitors in Mesa
Semaphores and Bounded Buffer Andy Wang Operating Systems COP 4610 / CGS 5765.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Implementing Synchronization. Synchronization 101 Synchronization constrains the set of possible interleavings: Threads “agree” to stay out of each other’s.
Starvation and Deadlock
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
The Synchronization Toolbox. Mutual Exclusion Race conditions can be avoiding by ensuring mutual exclusion in critical sections. Critical sections are.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
D u k e S y s t e m s More Synchronization featuring Producer/Consumer with Semaphores Jeff Chase Duke University.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
Threads and Concurrency. Threads A thread is a schedulable stream of control. defined by CPU register values (PC, SP) suspend: save register values in.
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:
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
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.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
IT 344: Operating Systems Winter 2008 Module 7 Semaphores and Monitors
Dining Philosophers & Monitors Questions answered in this lecture: How to synchronize dining philosophers? What are monitors and condition variables? What.
CS510 Concurrent Systems Jonathan Walpole. Introduction to Concurrency.
© 2004, D. J. Foreman 1 Monitors and Inter-Process Communication.
Operating Systems NWEN 301 Lecture 6 More Concurrency.
CS703 - Advanced Operating Systems
CSE 120 Principles of Operating
CS703 – Advanced Operating Systems
CIS Operating Systems Synchronization
Semaphores and Condition Variables
Threads and Synchronization
CSCI 511 Operating Systems Chapter 5 (Part C) Monitor
Threading And Parallel Programming Constructs
Critical section problem
CSE 451: Operating Systems Autumn Lecture 8 Semaphores and Monitors
CSE 451: Operating Systems Autumn Lecture 7 Semaphores and Monitors
Thread Synchronization including Mutual Exclusion
Chapter 6: Synchronization Tools
CSE 451: Operating Systems Winter Module 7 Semaphores and Monitors
Synchronization: Monitors
CSE 153 Design of Operating Systems Winter 19
CSE 153 Design of Operating Systems Winter 2019
Monitors and Inter-Process Communication
Review The Critical Section problem Peterson’s Algorithm
Presentation transcript:

Monitors and Semaphores

Annotated Condition Variable Example Condition *cv; Lock* cvMx; int waiter = 0; void await() { cvMx->Lock(); waiter = waiter + 1;/* “I’m sleeping” */ cv->Wait(cvMx);/* sleep */ cvMx->Unlock(); } void awake() { cvMx->Lock(); if (waiter) cv->Signal(cvMx); waiter = waiter - 1; CvMx->Unlock(); } Must hold lock when calling Wait. Wait atomically reacquires lock before returning. Wait atomically releases lock and sleeps until next Signal. Association with lock/mutex allows threads to safely manage state related to the sleep/wakeup coordination (e.g., waiters count).

The Roots of Condition Variables: Monitors A monitor is a “magic” module (a collection of procedures and state) with serialized execution and integrated wait/signal primitives. P1() P2() P3() P4() state ready to enter blocked wait() At most one thread may be active in a given monitor at any time. (exit) (enter) A thread may wait in the monitor, allowing another thread to enter. A thread in the monitor may signal a waiting thread, causing it to return from its wait and reenter the monitor. signal() CVs are easier to understand if we think about them in terms of the original monitor formulation. [Brinch Hansen 1973, C.A.R. Hoare 1974]

Hoare Semantics P1() P2() P3() P4() state ready to enter waiting wait() (exit) (enter) Hoare semantics: the signaled thread immediately takes over the monitor, and the signaler is suspended. signal() (Hoare) Hoare semantics allow the signaled thread to assume that the state has not changed since the signal that woke it up. Suppose purple signals, and a waiting blue is selected to wake up. suspended signal() (Hoare) The signaler does not continue in the monitor until the signaled thread exits or waits again.

Mesa Semantics P1() P2() P3() P4() state ready to (re)enter waiting wait() (exit) (enter) Mesa semantics: the signaled thread transitions back to the ready state (Nachos, Topaz, Java). signal() (Mesa) BUT: the signaled thread must examine the monitor state again after the wait, as the state may have changed since the signal. Suppose again that purple signals blue in the original example. There is no suspended state: the signaler continues until it exits the monitor or waits. The signaled thread contends with other ready threads to (re)enter the monitor and return from wait. Mesa semantics are easier to understand and implement... Loop before you leap!

From Monitors to Mx/Cv Pairs Mutexes and condition variables (as in Nachos) are based on the monitors concept, but they are more flexible. A monitor is “just like” a module whose state includes a mutex and a condition variable. The difference is syntactic; the basic semantics (and implementation) are the same for mutex/CV and monitors. It’s “just as if” the module’s methods Acquire the mutex on entry and Release the mutex before returning. But with mutexes, the critical regions within the methods can be defined at a finer grain, to allow more concurrency. With condition variables, the module methods may wait and signal on multiple independent conditions.

Mutual Exclusion in Java Mutexes and condition variables are built in to every Java object. no explicit classes for mutuxes and condition variables Every object is/has a “monitor”. At most one thread may “own” any given object’s monitor. A thread becomes the owner of an object’s monitor by executing a method declared as synchronized some methods may choose not to enforce mutual exclusion (unsynchronized) by executing the body of a synchronized statement or block synchronized construct specifies which object to acquire supports finer-grained locking than “pure monitors” allow exactly identical to the Modula-2 “LOCK(m) DO” construct in Birrell

Wait/Notify in Java public class Object { void notify(); /* signal */ void notifyAll(); /* broadcast */ void wait(); void wait(long timeout); } public class PingPong (extends Object) { public synchronized void PingPong() { while(true) { notify(); wait(); } Every Java object may be treated as a condition variable for threads using its monitor. A thread must own an object’s monitor to call wait/notify, else the method raises an IllegalMonitorStateException. Wait(*) waits until the timeout elapses or another thread notifies, then it waits some more until it can re-obtain ownership of the monitor: Mesa semantics. Loop before you leap!

Semaphores Semaphores handle all of your synchronization needs with one elegant but confusing abstraction. controls allocation of a resource with multiple instances a non-negative integer with special operations and properties initialize to arbitrary value with Init operation “souped up” increment (Up or V) and decrement (Down or P) atomic sleep/wakeup behavior implicit in P and V P does an atomic sleep, if the semaphore value is zero. P means “probe”; it cannot decrement until the semaphore is positive. V does an atomic wakeup. num(P) <= num(V) + init

Semaphores as Mutexes semapohore->Init(1); void Lock::Acquire() { semaphore->Down(); } void Lock::Release() { semaphore->Up(); } Semaphores must be initialized with a value representing the number of free resources: mutexes are a single-use resource. Down() to acquire a resource; blocks if no resource is available. Up() to release a resource; wakes up one waiter, if any. Mutexes are often called binary semaphores. However, “real” mutexes have additional constraints on their use. Up and Down are atomic.

Ping-Pong with Semaphores void PingPong() { while(not done) { blue->P(); Compute(); purple->V(); } void PingPong() { while(not done) { purple->P(); Compute(); blue->V(); } blue->Init(0); purple->Init(1);

Ping-Pong with One Semaphore? void PingPong() { while(not done) { Compute(); sem->V(); sem->P(); } sem->Init(0); blue: { sem->P(); PingPong(); } purple: { PingPong(); }

Ping-Pong with One Semaphore? void PingPong() { while(not done) { Compute(); sem->V(); sem->P(); } Nachos semaphores have Mesa-like semantics: They do not guarantee that a waiting thread wakes up “in time” to consume the count added by a V(). - semaphores are not “fair” - no count is “reserved” for a waking thread - uses “passive” vs. “active” implementation sem->Init(0); blue: { sem->P(); PingPong(); } purple: { PingPong(); }

Another Example With Dual Semaphores void Blue() { while(not done) { Compute(); purple->V(); blue->P(); } void Purple() { while(not done) { Compute(); blue->V(); purple->P(); } blue->Init(0); purple->Init(0);

Basic Barrier void IterativeCompute() { while(not done) { Compute(); purple->V(); blue->P(); } void IterativeCompute() { while(not done) { Compute(); blue->V(); purple->P(); } blue->Init(0); purple->Init(0);

How About This? (#1) void IterativeCompute?() { while(not done) { blue->P(); Compute(); purple->V(); } void IterativeCompute?() { while(not done) { purple->P(); Compute(); blue->V(); } blue->Init(1); purple->Init(1);

How About This? (#2) void IterativeCompute?() { while(not done) { blue->P(); Compute(); purple->V(); } void IterativeCompute?() { while(not done) { purple->P(); Compute(); blue->V(); } blue->Init(1); purple->Init(0);

How About This? (#3) void CallThis() { blue->P(); Compute(); purple->V(); } void CallThat() { purple->P(); Compute(); blue->V(); } blue->Init(1); purple->Init(0);

How About This? (#4) void CallThis() { blue->P(); Compute(); purple->V(); } void CallThat() { purple->P(); Compute(); blue->V(); } blue->Init(1); purple->Init(0);

Basic Producer/Consumer void Produce(int m) { empty->P(); buf = m; full->V(); } int Consume() { int m; full->P(); m = buf; empty->V(); return(m); } empty->Init(1); full->Init(0); int buf; This use of a semaphore pair is called a split binary semaphore: the sum of the values is always one.

A Bounded Resource int AllocateEntry() { int i; while (!FindFreeItem(&i)) block and wait for a free slot slot[i] = 1;/* grab free slot */ return(i); } void ReleaseEntry(int i) { slot[i] = 0; wakeup waiter, if any } boolean FindFreeItem(int* index) { for (i = 0; i < TableSize; i++) if (slot[i] == 0) return it; return (FALSE); }

A Bounded Resource with a Counting Semaphore semaphore->Init(N); int AllocateEntry() { int i; semaphore->Down(); ASSERT(FindFreeItem(&i)); slot[i] = 1; return(i); } void ReleaseEntry(int i) { slot[i] = 0; semaphore->Up(); } A semaphore for an N-way resource is called a counting semaphore. A caller that gets past a Down is guaranteed that a resource instance is reserved for it. Problems? Note: the current value of the semaphore is the number of resource instances free to allocate. But semaphores do not allow a thread to read this value directly. Why not?

Spin-Yield: Just Say No void Thread::Await() { awaiting = TRUE; while(awaiting) Yield(); } void Thread::Awake() { if (awaiting) awaiting = FALSE; }