Producer-Consumer Problem The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue.bufferqueue.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Synchronization NOTE to instructors: it is helpful to walk through an example such as readers/writers locks for illustrating the use of condition variables.
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.
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Monitors & Blocking Synchronization 1. Producers & Consumers Problem Two threads that communicate through a shared FIFO queue. These two threads can’t.
1 Condition Synchronization. 2 Synchronization Now that you have seen locks, is that all there is? No, but what is the “right” way to build a parallel.
CY2003 Computer Systems Lecture 05 Semaphores - Theory.
COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this?
1 Semaphores and Monitors: High-level Synchronization Constructs.
COSC 3407: Operating Systems Lecture 8: Semaphores, Monitors and Condition Variables.
CS 11 java track: lecture 7 This week: Web tutorial:
A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 6 Data Races and Memory Reordering Deadlock Readers/Writer Locks Condition.
Threading Part 4 CS221 – 4/27/09. The Final Date: 5/7 Time: 6pm Duration: 1hr 50mins Location: EPS 103 Bring: 1 sheet of paper, filled both sides with.
Threading Part 3 CS221 – 4/24/09. Teacher Survey Fill out the survey in next week’s lab You will be asked to assess: – The Course – The Teacher – The.
CSE332: Data Abstractions Lecture 24: Remaining Topics in Shared-Memory Concurrency Dan Grossman Spring 2010.
Synchronization Principles. Race Conditions Race Conditions: An Example spooler directory out in 4 7 somefile.txt list.c scores.txt Process.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Monitors CSCI 444/544 Operating Systems Fall 2008.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS444/CS544 Operating Systems Classic Synchronization Problems 2/26/2007 Prof. Searleman
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
CSE332: Data Abstractions Lecture 24: Readers/Writer Locks and Condition Variables Tyler Robison Summer
שירן חליבה Concurrent Queues. Outline: Some definitions 3 queue implementations : A Bounded Partial Queue An Unbounded Total Queue An Unbounded Lock-Free.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
Lecture 21 – CS2110 – Fall 2010 RACE CONDITIONS AND SYNCHRONIZATION.
Nachos Phase 1 Code -Hints and Comments
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
Midterm 1 – Wednesday, June 4  Chapters 1-3: understand material as it relates to concepts covered  Chapter 4 - Processes: 4.1 Process Concept 4.2 Process.
Internet Software Development Controlling Threads Paul J Krause.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
11/18/20151 Operating Systems Design (CS 423) Elsa L Gunter 2112 SC, UIUC Based on slides by Roy Campbell, Sam.
11/21/20151 Operating Systems Design (CS 423) Elsa L Gunter 2112 SC, UIUC Based on slides by Roy Campbell, Sam.
Synchronization Methods in Message Passing Model.
Stacks And Queues Chapter 18.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java Thread and Memory Model
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Synchronization.
1 CMSC421: Principles of Operating Systems Nilanjan Banerjee Principles of Operating Systems Acknowledgments: Some of the slides are adapted from Prof.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
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:
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
1 Previous Lecture Overview  semaphores provide the first high-level synchronization abstraction that is possible to implement efficiently in OS. This.
Dining Philosophers & Monitors Questions answered in this lecture: How to synchronize dining philosophers? What are monitors and condition variables? What.
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
3/17/2016cse synchronization-p2 © Perkins, DW Johnson and University of Washington1 Synchronization Part 2 CSE 410, Spring 2008 Computer.
Concurrency: Locks and synchronization Slides by Prof. Cox.
CS162 Section 2. True/False A thread needs to own a semaphore, meaning the thread has called semaphore.P(), before it can call semaphore.V() False: Any.
Lecture 5 Page 1 CS 111 Summer 2013 Bounded Buffers A higher level abstraction than shared domains or simple messages But not quite as high level as RPC.
pThread synchronization
CS703 - Advanced Operating Systems
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
CSE332: Data Abstractions Lecture 23: Data Races and Memory Reordering Deadlock Readers/Writer Locks Condition Variables Dan Grossman Spring 2012.
Synchronization Lecture 23 – Fall 2017.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Race Conditions & Synchronization
Producer-Consumer Problem
Software Engineering and Architecture
Don Porter Portions courtesy Emmett Witchel
Review The Critical Section problem Peterson’s Algorithm
Synchronization and liveness
Presentation transcript:

Producer-Consumer Problem The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue.bufferqueue –producer: generate a piece of data, put it into the buffer and start again. At the same time, –consumer: consumes the data (i.e., removing it from the buffer) one piece at a time. –The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer. The solution for the producer is to go to sleep if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer. generalized to have multiple producers and consumers. 1

Producer-Consumer Problem To motivate condition variables, consider the canonical example of a bounded buffer for sharing work among threads Bounded buffer: A queue with a fixed size –(Unbounded still needs a condition variable, but 1 instead of 2) For sharing work – think an assembly line: –Producer thread(s) do some work and enqueue result objects –Consumer thread(s) dequeue objects and do next stage –Must synchronize access to the queue 2 fedc buffer back front producer(s) enqueue consumer(s) dequeue

Code, attempt 1 3 class Buffer { E[] array = (E[])new Object[SIZE]; … // front, back fields, isEmpty, isFull methods synchronized void enqueue(E elt) { if(isFull()) ??? else … add to array and adjust back … } synchronized E dequeue() if(isEmpty()) ??? else … take from array and adjust front … }

Waiting enqueue to a full buffer should not raise an exception –Wait until there is room dequeue from an empty buffer should not raise an exception –Wait until there is data Bad approach is to spin (wasted work and keep grabbing lock) 4 void enqueue(E elt) { while(true) { synchronized(this) { if(isFull()) continue; … add to array and adjust back … return; }}} // dequeue similar

What we want Better would be for a thread to wait until it can proceed –Be notified when it should try again –In the meantime, let other threads run Like locks, not something you can implement on your own –Language or library gives it to you, typically implemented with operating-system support An ADT that supports this: condition variable –Informs waiter(s) when the condition that causes it/them to wait has varied Terminology not completely standard; will mostly stick with Java 5

Java approach: not quite right 6 class Buffer { … synchronized void enqueue(E elt) { if(isFull()) this.wait(); // releases lock and waits add to array and adjust back if(buffer was empty) this.notify(); // wake somebody up } synchronized E dequeue() { if(isEmpty()) this.wait(); // releases lock and waits take from array and adjust front if(buffer was full) this.notify(); // wake somebody up }

Key ideas Java weirdness: every object “is” a condition variable (and a lock) –other languages/libraries often make them separate wait: –“register” running thread as interested in being woken up –then atomically: release the lock and block –when execution resumes, thread again holds the lock notify: –pick one waiting thread and wake it up –no guarantee woken up thread runs next, just that it is no longer blocked on the condition – now waiting for the lock –if no thread is waiting, then do nothing 7

Bug #1 Between the time a thread is notified and it re-acquires the lock, the condition can become false again! 8 synchronized void enqueue(E elt){ if(isFull()) this.wait(); add to array and adjust back … } if(isFull()) this.wait(); add to array Time Thread 2 (dequeue) Thread 1 (enqueue) take from array if(was full) this.notify(); make full again Thread 3 (enqueue)

Bug fix #1 Guideline: Always re-check the condition after re-gaining the lock –In fact, for obscure reasons, Java is technically allowed to notify a thread spuriously (i.e., for no reason) 9 synchronized void enqueue(E elt) { while(isFull()) this.wait(); … } synchronized E dequeue() { while(isEmpty()) this.wait(); … }

Bug #2 If multiple threads are waiting, we wake up only one –Sure only one can do work now, but can’t forget the others! 10 while(isFull()) this.wait(); … Time Thread 2 (enqueue) Thread 1 (enqueue) // dequeue #1 if(buffer was full) this.notify(); // dequeue #2 if(buffer was full) this.notify(); Thread 3 (dequeues) while(isFull()) this.wait(); …

Bug fix #2 notifyAll wakes up all current waiters on the condition variable Guideline: If in any doubt, use notifyAll –Wasteful waking is better than never waking up So why does notify exist? –Well, it is faster when correct… 11 synchronized void enqueue(E elt) { … if(buffer was empty) this.notifyAll(); // wake everybody up } synchronized E dequeue() { … if(buffer was full) this.notifyAll(); // wake everybody up }

Alternate approach An alternative is to call notify (not notifyAll ) on every enqueue / dequeue, not just when the buffer was empty / full –Easy: just remove the if statement Alas, makes our code subtly wrong since it is technically possible that an enqueue and a dequeue are both waiting –See notes for the step-by-step details of how this can happen Works fine if buffer is unbounded since then only dequeuers wait 12