Monitors and Semaphores



Similar documents
Last Class: Semaphores

Lecture 6: Semaphores and Monitors

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

Semaphores and Monitors: High-level Synchronization Constructs

Outline of this lecture G52CON: Concepts of Concurrency

Mutual Exclusion using Monitors

Lecture 6: Introduction to Monitors and Semaphores

Monitors, Java, Threads and Processes

Monitors & Condition Synchronization

CS11 Java. Fall Lecture 7

Chapter 6 Concurrent Programming

Concurrent Programming

3C03 Concurrency: Condition Synchronisation

Topics. Producing Production Quality Software. Concurrent Environments. Why Use Concurrency? Models of concurrency Concurrency in Java

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

COS 318: Operating Systems. Semaphores, Monitors and Condition Variables

4. Monitors. Monitors support data encapsulation and information hiding and are easily adapted to an object-oriented environment.

Real Time Programming: Concepts

Parallel Programming

RT Language Classes. Real-Time Programming Languages (ADA and Esterel as Examples) Implementation. Synchroneous Systems Synchronous Languages

Thread Synchronization and the Java Monitor

Java Virtual Machine Locks

MonitorExplorer: A State Exploration-Based Approach to Testing Java Monitors

Lecture 8: Safety and Liveness Properties

Abstract. 1. Introduction. Butler W. Lampson Xerox Palo Alto Research Center David D. Redell Xerox Business Systems

Monitor Object. An Object Behavioral Pattern for Concurrent Programming. Douglas C. Schmidt

Chapter 8 Implementing FSP Models in Java

Concurrent programming in Java

Shared Address Space Computing: Programming

A Comparison Of Shared Memory Parallel Programming Models. Jace A Mogill David Haglin

Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis

Hoare-Style Monitors for Java

Figure 30.1: A Parent Waiting For Its Child What we would like to see here is the following output:

TESTING JAVA MONITORS BY STATE SPACE EXPLORATION MONICA HERNANDEZ. Presented to the Faculty of the Graduate School of

Java Concurrency Framework. Sidartha Gracias

Overview. CMSC 330: Organization of Programming Languages. Synchronization Example (Java 1.5) Lock Interface (Java 1.5) ReentrantLock Class (Java 1.

Advanced Multiprocessor Programming

Resurrecting Ada s Rendez-Vous in Java

6 Synchronization with Semaphores

Distributed Systems [Fall 2012]

Facing the Challenges for Real-Time Software Development on Multi-Cores

An Implementation Of Multiprocessor Linux

Java Memory Model: Content

SYSTEM ecos Embedded Configurable Operating System

Concurrency and Parallelism

OPERATING SYSTEMS PROCESS SYNCHRONIZATION

OBJECT ORIENTED PROGRAMMING LANGUAGE

CS Fall 2008 Homework 2 Solution Due September 23, 11:59PM

Synchronization. Todd C. Mowry CS 740 November 24, Topics. Locks Barriers

Concurrent Programming

How To Write A Multi Threaded Software On A Single Core (Or Multi Threaded) System

Overview Motivating Examples Interleaving Model Semantics of Correctness Testing, Debugging, and Verification

Priority Based Implementation in Pintos

A Look through the Android Stack

It is the thinnest layer in the OSI model. At the time the model was formulated, it was not clear that a session layer was needed.

W4118 Operating Systems. Instructor: Junfeng Yang

Chapter 2: Elements of Java

Deadlock Victim. dimanche 6 mai 12

Paper 3F6: Software Engineering and Systems Distributed Systems Design Solutions to Examples Paper 3

Concepts of Concurrent Computation

The Little Book of Semaphores

[Refer Slide Time: 05:10]

QoS for (Web) Applications Velocity EU 2011

Java the UML Way: Integrating Object-Oriented Design and Programming

Understanding Hardware Transactional Memory

Traditional Software Development. Model Requirements and JAVA Programs. Formal Verification & Validation. What is a state?

Understanding the Python GIL

Bounded Cost Algorithms for Multivalued Consensus Using Binary Consensus Instances

Chapter 6, The Operating System Machine Level

Design Patterns in C++

Process Modeling Notations and Workflow Patterns

OMPT and OMPD: OpenMP Tools Application Programming Interfaces for Performance Analysis and Debugging

Linux Driver Devices. Why, When, Which, How?

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Rigorous Software Development CSCI-GA

1.4 SOFTWARE CONCEPTS

(Pessimistic) Timestamp Ordering. Rules for read and write Operations. Pessimistic Timestamp Ordering. Write Operations and Timestamps

The ConTract Model. Helmut Wächter, Andreas Reuter. November 9, 1999

Priority Inversion Problem and Deadlock Situations

Threads 1. When writing games you need to do more than one thing at once.

Tasks Schedule Analysis in RTAI/Linux-GPL

Port of the Java Virtual Machine Kaffe to DROPS by using L4Env

Simple Cooperative Scheduler for Arduino ARM & AVR. Aka «SCoop»

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Crash Course in Java

Transcription:

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

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. [Brinch Hansen 1973, C.A.R. Hoare 1974] CVs are easier to understand if we think about them in terms of the original monitor formulation. ready to enter blocked (enter) signal() wait() state P1() P2() P3() P4() At most one thread may be active in a given monitor at any time. (exit) Athreadmaywait in the monitor, allowing another thread to enter. Athreadinthemonitormay signal a waiting thread, causing it to return from its wait and reenter the monitor. Hoare Semantics Suppose purple signals, and a waiting blue is selected to wake up. Hoare semantics: the signaled thread immediately takes over the monitor, and the signaler is suspended. ready to enter (enter) signal() (Hoare) state P1() P2() P3() P4() signal() (Hoare) (exit) suspended The signaler does not continue in the monitor until the signaled thread exits or waits again. waiting wait() Hoare semantics allow the signaled thread to assume that the state has not changed since the signal that woke it up. 2

Mesa Semantics Suppose again that purple signals blue in the original example. Mesa semantics: thesignaled thread transitions back to the ready state (Nachos, Topaz, Java). ready to (re)enter signal() (Mesa) (enter) state P1() P2() P3() P4() (exit) 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... waiting wait() BUT: the signaled thread must examine the monitor state again after the wait, asthe state may have changed since the signal. 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. 3

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 Every Java object may be treated as a condition variable for threads using its monitor. public class Object { notify(); /* signal */ notifyall(); /* broadcast */ wait(); wait(long timeout); public class PingPong (extends Object) { public synchronized PingPong() { while(true) { notify(); wait(); 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! 4

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); Lock::Acquire() { semaphore->down(); 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. Up and Down are atomic. Mutexes are often called binary semaphores. However, real mutexes have additional constraints on their use. 5

Ping-Pong with Semaphores blue->init(0); purple->init(1); PingPong() { PingPong() { Ping-Pong with One Semaphore? sem->init(0); blue: { sem->p(); PingPong(); purple: { PingPong(); PingPong() { while(not done){ sem->v(); sem->p(); 6

Ping-Pong with One Semaphore? sem->init(0); blue: { sem->p(); PingPong(); purple: { PingPong(); PingPong() { while(not done){ 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 Another Example With Dual Semaphores blue->init(0); purple->init(0); Blue() { while(not done){ Purple() { while(not done){ 7

Basic Barrier blue->init(0); purple->init(0); IterativeCompute() { IterativeCompute() { How About This? (#1) blue->init(1); purple->init(1); IterativeCompute?() { IterativeCompute?() { 8

How About This? (#2) blue->init(1); purple->init(0); IterativeCompute?() { IterativeCompute?() { How About This? (#3) blue->init(1); purple->init(0); CallThis() { CallThat() { 9

How About This? (#4) blue->init(1); purple->init(0); CallThis() { CallThat() { Basic Producer/Consumer empty->init(1); full->init(0); int buf; Produce(int m) { empty->p(); buf = m; full->v(); int Consume() { int m; full->p(); m = buf; empty->v(); return(m); This use of a semaphore pair is called a split binary semaphore:thesumofthe values is always one. 10

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); 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); 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? ReleaseEntry(int i) { slot[i] = 0; semaphore->up(); 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? 11

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