Semaphores and Monitors: High-level Synchronization Constructs

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

Last Class: Semaphores

Lecture 6: Semaphores and Monitors

Monitors, Java, Threads and Processes

Monitors and Semaphores

Concurrent Programming

Outline of this lecture G52CON: Concepts of Concurrency

Chapter 6 Concurrent Programming

Lecture 6: Introduction to Monitors and Semaphores

Parallel Programming

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

Monitors & Condition Synchronization

CS11 Java. Fall Lecture 7

3C03 Concurrency: Condition Synchronisation

Mutual Exclusion using Monitors

Thread Synchronization and the Java Monitor

Distributed Systems [Fall 2012]

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

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

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

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

Real Time Programming: Concepts

Concurrent programming in Java

Shared Address Space Computing: Programming

Hoare-Style Monitors for Java

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

6 Synchronization with Semaphores

Resurrecting Ada s Rendez-Vous in Java

Chapter 6, The Operating System Machine Level

Embedded Systems. 6. Real-Time Operating Systems

Java Virtual Machine Locks

SYSTEM ecos Embedded Configurable Operating System

The Little Book of Semaphores

Tasks Schedule Analysis in RTAI/Linux-GPL

W4118 Operating Systems. Instructor: Junfeng Yang

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

Processes and Non-Preemptive Scheduling. Otto J. Anshus

OPERATING SYSTEMS PROCESS SYNCHRONIZATION

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

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

Operating Systems Concepts: Chapter 7: Scheduling Strategies

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

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

CS423 Spring 2015 MP4: Dynamic Load Balancer Due April 27 th at 9:00 am 2015

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

Chapter 2: OS Overview

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

COMMMUNICATING COOPERATING PROCESSES

Java Concurrency Framework. Sidartha Gracias

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Multiprocessor Scheduling and Scheduling in Linux Kernel 2.6

Priority Based Implementation in Pintos

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

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

Understanding the Python GIL

Deadlock Victim. dimanche 6 mai 12

Lecture 8: Safety and Liveness Properties

Bounded Cost Algorithms for Multivalued Consensus Using Binary Consensus Instances

Thesis Proposal: Improving the Performance of Synchronization in Concurrent Haskell

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

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

Concurrent Programming

Programming real-time systems with C/C++ and POSIX

Operating Systems and Networks

Today. Binary addition Representing negative numbers. Andrew H. Fagg: Embedded Real- Time Systems: Binary Arithmetic

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Process Scheduling CS 241. February 24, Copyright University of Illinois CS 241 Staff

Linux Scheduler. Linux Scheduler

Priority Inversion Problem and Deadlock Situations

Chapter 1 FUNDAMENTALS OF OPERATING SYSTEM

Project No. 2: Process Scheduling in Linux Submission due: April 28, 2014, 11:59pm

A Survey of Parallel Processing in Linux

1.4 SOFTWARE CONCEPTS

CSC 2405: Computer Systems II

Road Map. Scheduling. Types of Scheduling. Scheduling. CPU Scheduling. Job Scheduling. Dickinson College Computer Science 354 Spring 2010.

W4118 Operating Systems. Instructor: Junfeng Yang

Real-Time Systems Prof. Dr. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Design Patterns in C++

Concepts of Concurrent Computation

First-class User Level Threads

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference.

Concurrency and Parallelism

Operating Systems 4 th Class

Comp 204: Computer Systems and Their Implementation. Lecture 12: Scheduling Algorithms cont d

Tuple spaces and Object spaces. Distributed Object Systems 12. Tuple spaces and Object spaces. Communication. Tuple space. Mechanisms 2.

Input / Output and I/O Strategies

Programming Languages

Performance Evaluation and Optimization of A Custom Native Linux Threads Library

Java Memory Model: Content

CSCI E 98: Managed Environments for the Execution of Programs

Transcription:

Semaphores and Monitors: High-level Synchronization Constructs 1 Synchronization Constructs Synchronization Coordinating execution of multiple threads that share data structures Past few lectures: Locks: provide mutual exclusion Condition variables: provide conditional synchronization Today: Historical perspective Monitors Alternate high-level language constructs Semaphores Introduced by Dijkstra in 1960s Main synchronization primitives in early operating systems 2

Introducing Monitors Separate the concerns of mutual exclusion and conditional synchronization What is a monitor? One lock, and Zero or more condition variables for managing concurrent access to shared data General approach: Collect related shared data into an object/module Define methods for accessing the shared data Monitors first introduced as programming language construct Calling a method defined in the monitor automatically acquires the lock Examples: Mesa, Java (synchronized methods) Monitors also define a programming convention Can be used in any language (C, C++, ) 3 Critical Section: Monitors Basic idea: Restrict programming model Permit access to shared variables only within a critical section General program structure Entry section Lock before entering critical section Wait if already locked Key point: synchronization may involve wait Critical section code Exit section Unlock when leaving the critical section Object-oriented programming style Associate a lock with each shared object Methods that access shared object are critical sections Acquire/release locks when entering/exiting a method that defines a critical section 4

Remember Condition Variables Locks Provide mutual exclusion Support two methods Lock::Acquire() wait until lock is free, then grab it Lock::Release() release the lock, waking up a waiter, if any Condition variables Support conditional synchronization Three operations Wait(): Release lock; wait for the condition to become true; reacquire lock upon return (Java wait()) Signal(): Wake up a waiter, if any (Java notify()) Broadcast(): Wake up all the waiters (Java notifyall()) Two semantics for implementation of wait() and signal() Hoare monitor semantics Hansen (Mesa) monitor semantics 5 Coke Machine Example Monitor Class CokeMachine{ Lock lock; int count = 0; Condition notfull, notempty; t Does the order of aquire/while(){wait matter? Order of release/signal matter? while (count == n) { notfull.wait(&lock); notempty.signal(); CokeMachine::Remove(){ while (count == 0) { notempty.wait(&lock); Remove coke from to the machine; count--; notfull.signal(); 6

Every monitor function should start with what? A. wait B. signal C. lock acquire D. lock release E. signalall 7 Hoare Monitors: Semantics Hoare monitor semantics: Assume thread T1 is waiting on condition x Assume thread T2 is in the monitor Assume thread T2 calls x.signal T2 gives up monitor, T2 blocks! T1 takes over monitor, runs T1 gives up monitor T2 takes over monitor, resumes Example fn1( ) x.wait // T1 blocks // T1 resumes Lock release(); fn4( ) x.signal T2 resumes // T2 blocks 8

Hansen (Mesa) Monitors: Semantics Hansen monitor semantics: Assume thread T1 waiting on condition x Assume thread T2 is in the monitor Assume thread T2 calls x.signal; g wake up T1 T2 continues, finishes When T1 get a chance to run,t1 takes over monitor, runs T1 finishes, gives up monitor Example: fn1( ) x.wait // T1 resumes // T1 finishes // T1 blocks fn4( ) x.signal // T2 continues // T2 finishes 9 Tradeoff Hoare Claims: Cleaner, good for proofs When a condition variable is signaled, it does not change Used in most textbooks but Inefficient implementation Not modular correctness depends on correct use and implementation of signal Hansen Signal is only a hint that the condition may be true Need to check condition again before proceeding Can lead to synchronization bugs Used by most systems (e.g., Java) Benefits: Efficient implementation Condition guaranteed to be true once you are out of while! if (count == n) { notfull.wait(&lock); notempty.signal(); while (count == n) { notfull.wait(&lock); notempty.signal(); 10

Problems with Monitors Nested Monitor Calls What happens when one monitor calls into another? What happens to CokeMachine::lock if thread sleeps in CokeTruck::Unload? What happens if truck unloader wants a coke? while (count == n) { notfull.wait(&lock); truck->unload(); notempty.signal(); CokeTruck::Unload(){ while (soda.atdoor()!= coke) { cokeavailable.wait(&lock); Unload soda closest to door; soda.pop(); Signal availability for soda.atdoor(); 11 More Monitor Headaches The priority inversion problem Three processes (P1, P2, P3), and P1 & P3 communicate using a monitor M. P3 is the highest priority process, followed by P2 and P1. 1. P1 enters M. 2. P1 is preempted by P2. 3. P2 is preempted by P3. 4. P3 tries to enter the monitor, and waits for the lock. 5. P2 runs again, preventing P3 from running, subverting the priority system. A simple way to avoid this situation is to associate with each monitor the priority of the highest priority process which ever enters that monitor. 12

Other Interesting Topics Exception handling What if a process waiting in a monitor needs to time out? Naked notify How do we synchronize with I/O devices that do not grab monitor locks, but can notify condition variables. Butler Lampson and David Redell, Experience with Processes and Monitors in Mesa. 13 Semaphores Study these for history and compatibility Don t use semaphores in new code A non-negative integer variable with two atomic and isolated operations Semaphore P() (Passeren; wait) If sem > 0, then decrement sem by 1 Otherwise wait until sem > 0 and then decrement Semaphore V() (Vrijgeven; signal) Increment sem by 1 Wake up a thread waiting in P() We assume that a semaphore is fair No thread t that is blocked on a P() operation remains blocked if the V() operation on the semaphore is invoked infinitely often In practice, FIFO is mostly used, transforming the set into a queue. 14

Important properties of Semaphores Semaphores are non-negative integers The only operations you can use to change the value of a semaphore are P() and V() (except for the initial setup) P() can block, but V() never blocks Semaphores are used both for Mutual exclusion, and Conditional synchronization Two types of semaphores Binary semaphores: Can either be 0 or 1 General/Counting semaphores: Can take any non-negative value Binary semaphores are as expressive as general semaphores (given one can implement the other) 15 How many possible values can a binary semaphore take? A. 0 B. 1 C. 2 D. 3 E. 4 16

Using Semaphores for Mutual Exclusion Use a binary semaphore for mutual exclusion Semaphore = new Semaphore(1); Semaphore P(); Critical Section; Semaphore V(); Using Semaphores for producer-consumer with bounded buffer int count; Semaphore mutex; Semaphore fullbuffers; Semaphore emptybuffers; Use a separate semaphore for each constraint 17 Coke Machine Example Coke machine as a shared buffer Two types of users Producer: Restocks the coke machine Consumer: Removes coke from the machine Requirements Only a single person can access the machine at any time If the machine is out of coke, wait until coke is restocked If machine is full, wait for consumers to drink coke prior to restocking How will we implement this? How many lock and condition variables do we need? A. 1 B. 2 C. 3 D. 4 E. 5 18

Revisiting Coke Machine Example Class CokeMachine{ int count; Semaphore new mutex(1); Semaphores new fullbuffers(0); Semaphores new emptybuffers(numbuffers); emptybuffers P(); mutex P(); mutex V(); fullbuffers V(); CokeMachine::Remove(){ fullbuffers P(); mutex P(); Remove coke from to the machine; count--; mutex V(); emptybuffers V(); Does the order of P matter? Order of V matter? 19 Implementing Semaphores Semaphore::P() { if (value == 0) { Put TCB on wait queue for semaphore; Switch(); // dispatch a ready thread else {value--; Does this work? Semaphore::V() { if wait queue is not empty { Move a waiting thread to ready queue; value++; 20

Implementing Semaphores Semaphore::P() { while (value == 0) { Put TCB on wait queue for semaphore; Switch(); // dispatch a ready thread value--; Semaphore::V() { if wait queue is not empty { Move a waiting thread to ready queue; value++; 21 The Problem with Semaphores Semaphores are used for dual purpose Mutual exclusion Conditional synchronization Difficult to read/develop code Waiting for condition is independent of mutual exclusion Programmer needs to be clever about using semaphores emptybuffers P(); mutex P(); mutex V(); fullbuffers V(); CokeMachine::Remove(){ fullbuffers P(); mutex P(); Remove coke from to the machine; count--; mutex V(); emptybuffers V(); 22

Comparing Semaphores and Monitors emptybuffers P(); mutex P(); mutex V(); fullbuffers V(); CokeMachine::Remove(){ fullbuffers P(); mutex P(); Remove coke from to the machine; count--; mutex V(); emptybuffers V(); Which is better? A. Semaphore B. Monitors while (count == n) { notfull.wait(&lock); notempty.notify(); CokeMachine::Remove(){ while (count == 0) { notempty.wait(&lock); Remove coke from to the machine; count--; notfull.notify(); 23 Summary Synchronization Coordinating execution of multiple threads that share data structures Past lectures: Locks provide mutual exclusion Condition variables provide conditional synchronization Today: Semaphores Introduced by Dijkstra in 1960s Two types: binary semaphores and counting semaphores Supports both mutual exclusion and conditional synchronization Monitors Separate mutual exclusion and conditional synchronization 24