Lecture 10: Introduction to Semaphores

Similar documents
CSCI 5828: Foundations of Software Engineering

Monitors & Condition Synchronization

Monitors & Condition Synchronization

Monitors & Condition Synchronisation

Monitors & Condition Synchronization

COMP30112: Concurrency Topics 5.2: Properties

CONCURRENT PROGRAMMING - EXAM

Lecture 9: Introduction to Monitors

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

Monitors; Software Transactional Memory

Lecture 21: Concurrency in Other Environments (Part 2)

Monitors; Software Transactional Memory

COMP 150-CCP Concurrent Programming. Lecture 12: Deadlock. Dr. Richard S. Hall

G52CON: Concepts of Concurrency

Last Class: Synchronization

$ Program Verification

Faculty of Computers & Information Computer Science Department

CS11 Java. Fall Lecture 7

Models of concurrency & synchronization algorithms

Safety & Liveness Properties

Chapter 6. Deadlock. DM519 Concurrent Programming

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

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

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

Lecture 8: September 30

What's wrong with Semaphores?

G52CON: Concepts of Concurrency

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

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Part IV Other Systems: I Java Threads

Shared Objects & Mutual Exclusion

Concurrency: State Models & Design Patterns

1 Process Coordination

Java Threads. COMP 585 Noteset #2 1

C340 Concurrency: Semaphores and Monitors. Goals

RACE CONDITIONS AND SYNCHRONIZATION

Threads and Parallelism in Java

EECS 482 Introduction to Operating Systems

Semaphores INF4140. Lecture 3. 0 Book: Andrews - ch.04 ( ) INF4140 ( ) Semaphores Lecture 3 1 / 34

Synchronization COMPSCI 386

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

COMP346 Winter Tutorial 4 Synchronization Semaphores

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

Performance Throughput Utilization of system resources

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

Lecture 29: Java s synchronized statement

Problems with Concurrency. February 19, 2014

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

Two Types of Semaphores

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Programming in Parallel COMP755

Multiple Inheritance. Computer object can be viewed as

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

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

Advanced Concepts of Programming

EE458 - Embedded Systems Lecture 8 Semaphores

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

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

CPS 310 second midterm exam, 11/14/2014

Concurrency in Java Prof. Stephen A. Edwards

CSC501 Operating Systems Principles. Process Synchronization

Lecture 7: Process & Thread Introduction

Dr. D. M. Akbar Hussain DE5 Department of Electronic Systems

CS 351 Design of Large Programs Threads and Concurrency

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

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

Introduction to OS Synchronization MOS 2.3

Chapter 6: Synchronization. Operating System Concepts 8 th Edition,

10/17/2011. Cooperating Processes. Synchronization 1. Example: Producer Consumer (3) Example

Concurrency 6 - Deadlock

THE QUEEN S UNIVERSITY OF BELFAST

Race Conditions & Synchronization

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

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

Chapter 32 Multithreading and Parallel Programming

Process Management And Synchronization

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Synchronization Lecture 24 Fall 2018

Semaphores and Monitors: High-level Synchronization Constructs

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

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

Multithreaded Programming

The University of Texas at Arlington

Shared-Memory and Multithread Programming

Process Synchronization

Deadlock. Lecture 4: Synchronization & Communication - Part 2. Necessary conditions. Deadlock handling. Hierarchical resource allocation

IV. Process Synchronisation

EECS 482 Introduction to Operating Systems

Synchronization: Semaphores

Question Points Score Total 100

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

Programming Language Concepts: Lecture 11

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

Synchronization in Java

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

Lecture 17: Sharing Objects in Java

Transcription:

COMP 150-CCP Concurrent Programming Lecture 10: Introduction to Semaphores Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 19, 2008

Semaphores Semaphores (Dijkstra 1968) are widely used for dealing with inter-process synchronization in operating systems. A semaphore s is an integer variable that can hold only non-negative values. The only operations permitted on s are up(s) (V = vrijgeven = release) and down(s) (P = passeren = pass). Blocked processes are held in a FIFO queue. down(s): if (s > 0) then decrement s else block execution of the calling process up(s): if (processes blocked on s) then awaken one of them else increment s

Modeling Semaphores To ensure analyzable models, 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] = (up->sema[v+1] when(v>0) down->sema[v-1]), SEMA[Max+1] = ERROR. LTS?

Modeling Semaphores Action down is only accepted when value v of the semaphore is greater than 0. Action up is not guarded. Trace to a violation up up up up

Semaphore Example Three processes p[1..3] use a shared mutex semaphore to ensure mutually exclusive access to critical region (i.e., access to some shared resource). LOOP = (mutex.down->critical->mutex.up->loop). SEMADEMO = (p[1..3]:loop {p[1..3]::mutex:semaphore(1)). 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?

Semaphore Example

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; public synchronized void up() { ++value; notify(); public synchronized void down() throws InterruptedException { while (value == 0) wait(); --value; Why notify() not notifyall()? Why no notify() in down()?

Bounded Buffer Example A bounded buffer consists of a fixed number of slots. Items are put 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.

Semaphore Bounded Buffer Model The behavior of BOUNDEDBUFFER is independent of the actual data values, and so can be modeled in a data-independent manner. const Max = 5 range Int = 0..Max SEMAPHORE...as before... BUFFER = (put -> empty.down -> full.up ->BUFFER get -> full.down -> empty.up ->BUFFER ). PRODUCER = (put -> PRODUCER). CONSUMER = (get -> CONSUMER). BOUNDEDBUFFER = (PRODUCER BUFFER CONSUMER empty:semaphore(5) items:semaphore(0)) @{put,get.

Java Semaphore Bounded Buffer We use two semaphores full and empty to reflect the state of the buffer, instead of condition variables. We create a separate buffer public interface Buffer { public class SemaBuffer implements Buffer { Semaphore items; //counts number of items Semaphore spaces; //counts number of spaces interface to permit alternative implementations. public SemaBuffer(int size) { this.size = size; buf = new Object[size]; items = new Semaphore(0); spaces = new Semaphore(size);

Java Semaphore Bounded Buffer spaces is decremented during the put()operation, which is blocked if spaces is zero; items is decremented by the get() operation, which is blocked if items is zero. public synchronized void put(object o) throws InterruptedException { spaces.down(); buf[in] = o; ++count; in = (in+1) % size; items.up(); public synchronized Object get() throws InterruptedException { items.down(); Object o = buf[out]; buf[out] = null; --count; out = (out+1) % size; spaces.up(); return o;

Java Bounded Buffer Producer public class Producer implements Runnable { private Buffer buf; private String alphabet = "abcdefghijklmnopqrstuvwxyz"; private boolean paused = true; public Producer(Buffer b) { buf = b; public synchronized void pause() { paused =!paused; notify(); public void run() { try { int ai = 0; while (true) { synchronized (this) { while (paused) { wait(); buf.put(new Character(alphabet.charAt(ai))); ai = (ai + 1) % alphabet.length(); Thread.sleep(500); catch (InterruptedException ex) { Consumer is similar but calls buf.get().

Nested Monitor Problem LTSA analysis predicts a possible deadlock: Composing potential DEADLOCK States Composed: 28 Transitions: 32 in 60ms Trace to DEADLOCK: get The Consumer tries to get a character, but the buffer is empty. It blocks and releases the lock on the semaphore items. The Producer tries to put a character into the buffer, but also blocks. Why? This situation is known as the nested monitor problem.

Nested Monitor Program Fix 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 put(object o) throws InterruptedException { spaces.down(); synchronized (this){ buf[in] = o; ++count; in = (in+1) % size; items.up();

Nested Monitor Model Fix BUFFER = (put -> BUFFER get -> BUFFER). PRODUCER = (spaces.down->put->items.up->producer). CONSUMER = (items.down->get->spaces.up->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?

Nested Monitor Program Fix Or perhaps use a mutex semaphore, rather than mixing monitors and semaphores.... Semaphore items; //counts number of items Semaphore spaces; //counts number of spaces Semaphore mutex; //control access to critical region public SemaBuffer(int size) { this.size = size; buf = new Object[size]; items = new Semaphore(0); spaces = new Semaphore(size); mutex = new Semaphore(1); public void put(object o) throws InterruptedException { spaces.down(); mutex.down(); buf[in] = o; ++count; in = (in+1) % size; mutex.up(); items.up();...

Monitor Bounded Buffer Model Since monitors are higher level than semaphores, the BOUNDEDBUFFER model and Java implementation are more straightforward using monitors. BUFFER(N=5) = COUNT[0], COUNT[i:0..N] = (when (i<n) put->count[i+1] when (i>0) get->count[i-1] ). PRODUCER = (put->producer). CONSUMER = (get->consumer). BOUNDEDBUFFER = (PRODUCER BUFFER(5) CONSUMER). (similar to the Parking Lot example)

Java Monitor Bounded Buffer class MonitorBuffer implements Buffer { public synchronized void put(object o) throws InterruptedException { while (count == size) wait(); buf[in] = o; ++count; in = (in+1) % size; notifyall(); public synchronized Object get() throws InterruptedException { while (count == 0) wait(); Object o = buf[out]; buf[out] = null; --count; out = (out+1) % size; notifyall(); return o;