Monitors & Condition Synchronization

Similar documents
CSCI 5828: Foundations of Software Engineering

Monitors & Condition Synchronization

Monitors & Condition Synchronization

Lecture 10: Introduction to Semaphores

Monitors & Condition Synchronisation

C340 Concurrency: Semaphores and Monitors. Goals

Lecture 9: Introduction to Monitors

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

COMP30112: Concurrency Topics 5.2: Properties

Communications Software Engineering Condition Synchronization and Liveness

$ Program Verification

Chapter 6. Deadlock. DM519 Concurrent Programming

Shared Objects & Mutual Exclusion

CONCURRENT PROGRAMMING - EXAM

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

G52CON: Concepts of Concurrency

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory

Safety & Liveness Properties

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Answer the first question and two further questions. i. action prefix ( -> ) [3 marks]

What's wrong with Semaphores?

Chapter 10. Message Passing. Concurrency: message passing 1. Magee/Kramer

Processes & Threads. Concepts: processes - units of sequential execution.

Chapter 2. Processes & Threads. Concurrency: processes & threads 1. Magee/Kramer

1 Process Coordination

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set?

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Chapter 10. Message Passing. Concurrency: message passing 1. Magee/Kramer 2 nd Edition

Concurrency 6 - Deadlock

Lecture 8: September 30

Resource management. Real-Time Systems. Resource management. Resource management

Concurrency: State Models & Design Patterns

CSCI 5828: Foundations of Software Engineering

Faculty of Computers & Information Computer Science Department

Process Management And Synchronization

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Introduction to OS Synchronization MOS 2.3

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Models of concurrency & synchronization algorithms

Real-Time Systems. Lecture #4. Professor Jan Jonsson. Department of Computer Science and Engineering Chalmers University of Technology

Synchronization COMPSCI 386

Multitasking / Multithreading system Supports multiple tasks

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Java Threads. COMP 585 Noteset #2 1

Last Class: Synchronization

2.c Concurrency Mutual exclusion & synchronization mutexes. Unbounded buffer, 1 producer, N consumers

Synchronization SPL/2010 SPL/20 1

Concurrent processes. Processes and Threads. Processes and threads. Going back to Concurrency. Modelling Processes. Modeling processes

Threads and Parallelism in Java

The University of Texas at Arlington

Programming in Parallel COMP755

The University of Texas at Arlington

CS 31: Intro to Systems Misc. Threading. Kevin Webb Swarthmore College December 6, 2018

CS11 Java. Fall Lecture 7

RACE CONDITIONS AND SYNCHRONIZATION

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

THE QUEEN S UNIVERSITY OF BELFAST

Interprocess Communication By: Kaushik Vaghani

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

CHAPTER 6: PROCESS SYNCHRONIZATION

EECS 482 Introduction to Operating Systems

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Semaphores. A semaphore is an object that consists of a. methods (e.g., functions): signal and wait. semaphore. method signal. counter.

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University

CPS 310 second midterm exam, 11/14/2014

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018

Software Architecture

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)

Chapter 6: Process Synchronization

Only one thread can own a specific monitor

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

3C03 Concurrency: Starvation and Deadlocks

Concurrency: a crash course

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6.

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS

Part IV Other Systems: I Java Threads

Chapter 6: Process Synchronization

CSE 153 Design of Operating Systems

Race Conditions & Synchronization

Reminder from last time

Operating Systems ECE344

Deadlock. INF2140 Parallel Programming: Lecture 6. March 07, INF2140 Parallel Programming: Lecture 6 Deadlock

Chapter 6: Process Synchronization

Verification Finite-state process modeling and reachability analysis

Outline. Monitors. Barrier synchronization The sleeping barber problem Readers and Writers One-way tunnel. o Monitors in Java

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

G52CON: Concepts of Concurrency

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Opera&ng Systems ECE344

Multiple Inheritance. Computer object can be viewed as

Transcription:

Chapter 5 Monitors & Condition Synchronization monitors & condition synchronization Concepts: monitors: encapsulated data + access procedures mutual exclusion + condition synchronization single access procedure active in the monitor nested monitors Models: guarded actions Practice: private data and synchronized methods (exclusion wait(), notify() and notifyall() for condition synch. single thread active in the monitor at a time Concurrency: monitors & condition synchronization 1 Concurrency: monitors & condition synchronization 2 5.1 Condition synchronization carpark model Events or actions of interest? arrive and depart Identify processes. arrivals, departures and carpark control Define each process and interactions (structure A controller is required for a carpark, which only permits cars to enter when the carpark is not full and does not permit cars to leave when there are no cars in the carpark. Car arrival and departure are simulated by separate threads. Concurrency: monitors & condition synchronization 3 ARRIVALS arrive CONTROL depart DEPARTURES Concurrency: monitors & condition synchronization 4 carpark model CONTROL(N=4) = SPACES[N], SPACES[i:0..N] = (when(i>0) arrive->spaces[i-1] when(i<n) depart->spaces[i+1] ARRIVALS = (arrive->arrivals DEPARTURES = (depart->departures = (ARRIVALS CONTROL(4) DEPARTURES Guarded actions are used to control arrive and depart. LTS? Concurrency: monitors & condition synchronization 5 carpark program Model - all entities are processes interacting by actions Program - need to identify threads and monitors thread - active entity which initiates (out) actions monitor - passive entity which responds to (in) actions. For the carpark? ARRIVALS arrive CONTROL depart DEPARTURES Concurrency: monitors & condition synchronization 6

carpark program - class diagram Applet CarPark cardisplay arrivals, departures CarParkCanvas ThreadPanel disp Arrivals Departures CarParkControl arrive() depart() DisplayCarPark Runnable carpark We have omitted DisplayThread and GraphicCanvas threads managed by ThreadPanel. Concurrency: monitors & condition synchronization 7 carpark program Arrivals and Departures implement Runnable, CarParkControl provides the control (condition synchronization Instances of these are created by the start() method of the CarPark applet : public void start() { CarParkControl c = new DisplayCarPark(carDisplay,Places); arrivals.start(new Arrivals(c)); departures.start(new Departures(c)); Concurrency: monitors & condition synchronization 8 carpark program - Arrivals and Departures threads class Arrivals implements Runnable { CarParkControl carpark; Arrivals(CarParkControl c) {carpark = c; public void run() { try { while(true) { Similarly Departures ThreadPanel.rotate(330); which calls carpark.arrive(); carpark.depart( ThreadPanel.rotate(30); catch (InterrtedException e){ How do we implement the control of CarParkControl? Concurrency: monitors & condition synchronization 9 Carpark program - CarParkControl monitor class CarParkControl { protected int spaces; protected int capacity; CarParkControl(int n) {capacity = spaces = n; synchronized void arrive() { --spaces; synchronized void depart() { ++spaces; mutual exclusion by synch methods condition synchronization? block if full? (spaces==0) block if empty? (spaces==n) Concurrency: monitors & condition synchronization 10 condition synchronization in Java Java provides a thread wait set per monitor (actually per object) with the following methods: public final void notify() Wakes a single thread that is waiting on this object's set. public final void notifyall() Wakes all threads that are waiting on this object's set. public final void wait() throws InterrtedException Waits to be notified by another thread. The waiting thread releases the synchronization lock associated with the monitor. When notified, the thread must wait to reacquire the monitor before resuming execution. Concurrency: monitors & condition synchronization 11 condition synchronization in Java We refer to a thread entering a monitor when it acquires the mutual exclusion lock associated with the monitor and exiting the monitor when it releases the lock. Wait() - causes the thread to exit the monitor, permitting other threads to enter the monitor. Thread A notify() Monitor data wait() Thread B Concurrency: monitors & condition synchronization 12

condition synchronization in Java FSP: when cond act -> NEWSTAT Java: public synchronized void act() throws InterrtedException { while (!cond) wait(); // modify monitor data notifyall() CarParkControl - condition synchronization class CarParkControl { protected int spaces; protected int capacity; CarParkControl(int n) {capacity = spaces = n; synchronized void arrive() while (spaces==0) wait(); --spaces; The while loop is necessary to retest the condition cond to ensure that synchronized void depart() while (spaces==capacity) wait(); cond is indeed satisfied when it re-enters the monitor. ++spaces; notifyall() is necessary to awaken other thread(s) that may be Why is it safe to use notify() waiting Concurrency: to monitors enter & condition the monitor synchronization now that the monitor data has been changed. here rather than notifyall()? 13 Concurrency: monitors & condition synchronization 14 models to monitors - summary Active entities (that initiate actions) are implemented as threads. Passive entities (that respond to actions) are implemented as monitors. Each guarded action in the model of a monitor is implemented as a synchronized method which uses a while loop and wait() to implement the guard. The while loop condition is the negation of the model guard condition. Changes in the state of the monitor are signaled to waiting threads using notify() or notifyall( 5.2 Semaphores Semaphores are widely used for dealing with inter-process synchronization in operating systems. Semaphore s is an integer variable that can take only non-negative values. The only operations permitted on s are (s) and down(s Blocked processes are held in a FIFO queue. down(s): if s >0 then decrement s else block execution of the calling process (s): if processes blocked on s then awaken one of them else increment s Concurrency: monitors & condition synchronization 15 Concurrency: monitors & condition synchronization 16 modeling semaphores To ensure analyzability, we only model semaphores that take a finite range of values. If this range is exceeded then we regard this as an ERROR. N is the initial value. const Max = 3 range Int = 0..Max SEMAPHORE(N=0) = SEMA[N], SEMA[v:Int] = (->SEMA[v+1] when(v>0) down->sema[v-1] ), SEMA[Max+1] = ERROR. LTS? Concurrency: monitors & condition synchronization 17 modeling semaphores -1 0 1 2 3 down Action down is only accepted when value v of the semaphore is greater than 0. Action is not guarded. Trace to a violation: Concurrency: monitors & condition synchronization 18 down down

semaphore demo - model Three processes p[1..3] use a shared semaphore mutex to ensure mutually exclusive access (action critical) to some resource. LOOP = (mutex.down->critical->mutex.->loop SEMADEMO = (p[1..3]:loop {p[1..3]::mutex:semaphore(1) semaphore demo - model p.1.mutex.down p.2.mutex.down p.3.mutex.down p.3.critical p.2.critical p.1.critical 0 1 2 3 4 5 6 For mutual exclusion, the semaphore initial value is 1. Why? Is the ERROR state reachable for SEMADEMO? Is a binary semaphore sufficient (i.e. Max=1)? LTS? Concurrency: monitors & condition synchronization 19 p.3.mutex. p.2.mutex. p.1.mutex. Concurrency: monitors & condition synchronization 20 semaphores in Java Semaphores are passive objects, therefore implemented as monitors. (In practice, semaphores are a low-level mechanism often used in implementing the higher-level monitor construct.) public class Semaphore { private int value; public Semaphore (int initial) {value = initial; synchronized public void () { ++value; synchronized public void down() while (value== 0) wait(); --value; Concurrency: monitors & condition synchronization 21 SEMADEMO display current semaphore value thread 1 is executing critical actions. thread 2 is blocked waiting. thread 3 is executing non-critical actions. Concurrency: monitors & condition synchronization 22 SEMADEMO What if we adjust the time that each thread spends in its critical section? large resource requirement - more conflict? (eg. more than 67% of a rotation)? small resource requirement - no conflict? (eg. less than 33% of a rotation)? Hence the time a thread spends in its critical section should be kept as short as possible. Concurrency: monitors & condition synchronization 23 SEMADEMO program - revised ThreadPanel class public class ThreadPanel extends Panel { // construct display with title and rotating arc color c public ThreadPanel(String title, Color c) { // hasslider == true creates panel with slider public ThreadPanel (String title, Color c, boolean hasslider) { // rotate display of currently running thread 6 degrees // return false when in initial color, return true when in second color public static boolean rotate() // rotate display of currently running thread by degrees public static void rotate(int degrees) // create a new thread with tar r and start it running public void start(runnable r) { // stop the thread using Thread.interrt() public void stop() { Concurrency: monitors & condition synchronization 24

SEMADEMO program - MutexLoop class MutexLoop implements Runnable { Semaphore mutex; MutexLoop (Semaphore sema) {mutex=sema; Threads and semaphore are created by the applet start() method. public void run() { try { while(true) { while(!threadpanel.rotate()); mutex.down(); // mutual exclusion while(threadpanel.rotate()); //critical actions mutex.(); //release mutual exclusion catch(interrtedexception e){ ThreadPanel.rotate() returns false while executing non-critical actions (dark color) and true otherwise. Concurrency: monitors & condition synchronization 25 5.3 Bounded Buffer A bounded buffer consists of a fixed number of slots. Items are into the buffer by a producer process and removed by a consumer process. It can be used to smooth out transfer rates between the producer and consumer. (see car park example) Concurrency: monitors & condition synchronization 26 bounded buffer - a data-independent model BOUNDEDBUFFER PRODUCER BUFFER CONSUMER The behaviour of BOUNDEDBUFFER is independent of the actual data values, and so can be modelled in a dataindependent manner. LTS: Concurrency: monitors & condition synchronization 27 0 1 2 3 4 5 bounded buffer - a data-independent model BUFFER(N=5) = COUNT[0], COUNT[i:0..N] = (when (i<n) ->COUNT[i+1] when (i>0) ->COUNT[i-1] PRODUCER = (->PRODUCER CONSUMER = (->CONSUMER BOUNDEDBUFFER = (PRODUCER BUFFER(5) CONSUMER Concurrency: monitors & condition synchronization 28 bounded buffer program - buffer monitor public interface Buffer { We separate the class BufferImpl implements Buffer { interface to permit an public synchronized void (Object o) alternative implementation while (count==size) wait(); buf[in] = o; ++count; in=(in+1)%size; later. public synchronized Object () while (count==0) wait(); Object o =buf[out]; buf[out]=null; --count; out=(out+1)%size; return (o); Concurrency: monitors & condition synchronization 29 bounded buffer program - producer process class Producer implements Runnable { Buffer buf; String alphabet= "abcdefghijklmnopqrstuvwxyz"; Producer(Buffer b) {buf = b; public void run() { Similarly Consumer try { which calls buf.( int ai = 0; while(true) { ThreadPanel.rotate(12); buf.(new Character(alphabet.charAt(ai))); ai=(ai+1) % alphabet.length(); ThreadPanel.rotate(348); catch (InterrtedException e){ Concurrency: monitors & condition synchronization 30

5.4 Nested Monitors Spose that, in place of using the count variable and condition synchronization directly, we instead use two semaphores full and empty to reflect the state of the buffer. class SemaBuffer implements Buffer { Semaphore full; //counts number of items Semaphore empty; //counts number of spaces SemaBuffer(int size) { this.size = size; buf = new Object[size]; full = new Semaphore(0); empty= new Semaphore(size); Concurrency: monitors & condition synchronization 31 nested monitors - bounded buffer program synchronized public void (Object o) empty.down(); buf[in] = o; ++count; in=(in+1)%size; full.(); synchronized public Object () throws InterrtedException{ full.down(); Object o =buf[out]; buf[out]=null; --count; out=(out+1)%size; empty.(); return (o); Does this behave as desired? empty is decremented during a operation, which is blocked if empty is zero; full is decremented by a operation, which is blocked if full is zero. Concurrency: monitors & condition synchronization 32 nested monitors - bounded buffer model const Max = 5 range Int = 0..Max SEMAPHORE...as before... BUFFER = ( -> empty.down ->full. ->BUFFER -> full.down ->empty. ->BUFFER PRODUCER = ( -> PRODUCER CONSUMER = ( -> CONSUMER BOUNDEDBUFFER = (PRODUCER BUFFER CONSUMER empty:semaphore(5) full:semaphore(0) )@{,. Does this behave as desired? Concurrency: monitors & condition synchronization 33 nested monitors - bounded buffer model LTSA analysis predicts a possible DEADLOCK: Composing potential DEADLOCK States Composed: 28 Transitions: 32 in 60ms Trace to DEADLOCK: The Consumer tries to a character, but the buffer is empty. It blocks and releases the lock on the semaphore full. The Producer tries to a character into the buffer, but also blocks. Why? This situation is known as the nested monitor problem. Concurrency: monitors & condition synchronization 34 nested monitors - revised bounded buffer program The only way to avoid it in Java is by careful design. In this example, the deadlock can be removed by ensuring that the monitor lock for the buffer is not acquired until after semaphores are decremented. public void (Object o) empty.down(); synchronized(this){ buf[in] = o; ++count; in=(in+1)%size; full.(); Concurrency: monitors & condition synchronization 35 nested monitors - revised bounded buffer model BUFFER = ( -> BUFFER -> BUFFER PRODUCER =(empty.down->->full.->producer CONSUMER =(full.down->->empty.->consumer The semaphore actions have been moved to the producer and consumer. This is exactly as in the implementation where the semaphore actions are outside the monitor. Does this behave as desired? Minimized LTS? Concurrency: monitors & condition synchronization 36

5.5 Monitor invariants An invariant for a monitor is an assertion concerning the variables it encapsulates. This assertion must hold whenever there is no thread executing inside the monitor i.e. on thread entry to and exit from a monitor. CarParkControl Invariant: 0 spaces N Semaphore Invariant: Buffer Invariant: 0 value 0 count size and 0 in < size and 0 out< size and in = (out + count) modulo size Invariants can be helpful in reasoning about correctness of monitors using a logical proof-based approach. Generally we prefer to use a model-based approach amenable to mechanical checking. Concurrency: monitors & condition synchronization 37 Summary Concepts monitors: encapsulated data + access procedures mutual exclusion + condition synchronization nested monitors Model guarded actions Practice private data and synchronized methods in Java wait(), notify() and notifyall() for condition synchronization single thread active in the monitor at a time Concurrency: monitors & condition synchronization 38