Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.

Slides:



Advertisements
Similar presentations
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Advertisements

CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems.
1Deadlock DeadlockedBankAccount –withdraw(){ lock.lock(); while(balance
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.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  synchronized methods and statements  wait.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
02/05/2008CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying an earlier.
1 Lecture 18 Further Threading Overview  Case Study: Cooperating Threads  Producer/ Consumer model threads  Waiting for Synchronized Data  Busy Waiting.
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
1 Semaphores and Monitors: High-level Synchronization Constructs.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
11-Jun-15 Producer-Consumer An example of using Threads.
02/05/2007CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook.
1 Thread Pools Representation and Management of Data on the Internet.
16-Jun-15 Producer-Consumer An example of using Threads.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L21 (Chapter 24) Multithreading.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
28-Jun-15 Producer-Consumer An example of using Threads.
ThreadThread Thread Basics Thread Synchronization Animations.
Definitions Process – An executing program
Threads Just Java: C10–pages 251- C11–pages 275-
Garbage Collection CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Methods CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threading Eriq Muhammad Adams J
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Parallel Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
System Programming Practical Session 4: Concurrency / Safety.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Semaphores CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Chapter 71 Monitors (7.7)  A high-level-language object-oriented concept that attempts to simplify the programming of synchronization problems  A synchronization.
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Networking Code CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
1 Java Programming Java Programming II Concurrent Programming: Threads ( II)
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
Thread Pools CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Principles of Software Development
Chapter 30 Multithreading and Parallel Programming
COEN346 Tutorial Monitor Objects.
Multithreading Chapter 9.
Lecture 24 Concurrency 2 (D&D 23) Date.
CS510 Operating System Foundations
CS510 Operating System Foundations
Monitors Chapter 7.
Lecture 9: Process Synchronization
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Thread Synchronization
Counter in Java class Counter { private integer count = 0; public void Increment() synchronized { ++count; } public integer GetCount() synchronized.
Principles of Software Development
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Monitors Chapter 7.
Software Engineering and Architecture
Presentation transcript:

Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L

Outline USC CSCI 201L2/9 ▪P▪Producer/Consumer ▪P▪Program

Producer/Consumer Overview ▪The producer/consumer problem is a famous problem for concurrent programming ▪Assume you have a soda machine with a number of delivery people (producers) and a number of people wanting to buy sodas (consumers) ›Each producer can insert as many sodas as he has, up to the capacity of the soda machine ›Each consumer can purchase as many sodas as he wants, up to the current number in the soda machine ▪If there are not enough sodas for a consumer to buy, he needs to wait until there are ▪If there is not enough room for the producer to insert the number of sodas he has, he needs to wait until there is ▪This problem can produce a situation called deadlock ▪Download the ProducerConsumerWithMonitors.java from the course web site and execute it ›What line(s) of code produce the potential deadlock? USC CSCI 201L3/9 Producer/Consumer

Producer/Consumer Example with Monitors 1 import java.util.LinkedList; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 5 public class ProducerConsumerWithMonitors { 6 private static Buffer buffer = new Buffer(); 7 8 public static void main(String [] args) { 9 ExecutorService executor = Executors.newFixedThreadPool(2); 10 executor.execute(new ProducerTask()); 11 executor.execute(new ConsumerTask()); 12 executor.shutdown(); 13 } private static class ProducerTask implements Runnable { 16 public void run() { 17 try { 18 int i = 1; 19 while (true) { 20 System.out.println("Producer writes: " + i); 21 buffer.write(i++); 22 Thread.sleep((int)(Math.random() * 1000)); 23 } 24 } catch (InterruptedException ie) { 25 System.out.println("Producer IE: " + ie.getMessage()); 26 } 27 } 28 } private static class ConsumerTask implements Runnable { 31 public void run() { 32 try { 33 while (true) { 34 System.out.println("\t\tConsumer reads: " + buffer.read()); 35 Thread.sleep((int)(Math.random() * 1000)); 36 } 37 } catch (InterruptedException ie) { 38 System.out.println("Consumer IE: " + ie.getMessage()); 39 } 40 } 41 } USC CSCI 201L4/9 Producer/Consumer 42 private static class Buffer { 43 private static final int CAPACITY = 1; 44 private LinkedList queue = new LinkedList (); 45 private static Object notEmpty = new Object(); 46 private static Object notFull = new Object(); public void write(int value) { 49 synchronized(notFull) { 50 synchronized(notEmpty) { 51 try { 52 while (queue.size() == CAPACITY) { 53 System.out.println("Wait for notFull condition " + value); 54 notFull.wait(); 55 } 56 queue.offer(value); 57 notEmpty.notify(); 58 } catch (InterruptedException ie) { 59 System.out.println("Buffer.write IE: " + ie.getMessage()); 60 } 61 } 62 } 63 } public int read() { 66 int value = 0; 67 synchronized(notFull) { 68 synchronized(notEmpty) { 69 try { 70 while (queue.isEmpty()) { 71 System.out.println("\t\tWait for notEmpty condition"); 72 notEmpty.wait(); 73 } 74 value = queue.remove(); 75 notFull.notify(); 76 } catch (InterruptedException ie) { 77 System.out.println("Buffer.read IE: " + ie.getMessage()); 78 } 79 } 80 } 81 return value; 82 } 83 } // ends class Buffer 84 } // ends class ProducerConsumerWithMonitors

Monitors, Locks, Semaphores ▪Monitors are an older technology that allow us to synchronize specific blocks of code or methods ›There is the potential of deadlock that can be caused when multiple blocks of code need to be synchronized on multiple objects (as in the previous example) ▪Locks provide the underlying mechanism for monitors, but we can also explicitly define our own locks ›This allows us to create multiple conditions on a single lock, providing the ability to avoid the deadlock problem allowed by monitors ▪Semaphores allow more than one thread to obtain permits to access a specific block of code ›This would be equivalent to having more than one of the same lock available on a block of code ›We will talk about semaphores in a future lecture USC CSCI 201L5/9 Producer/Consumer

Producer/Consumer Example with Locks/Conditions 1 import java.util.LinkedList; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 import java.util.concurrent.locks.Condition; 5 import java.util.concurrent.locks.Lock; 6 import java.util.concurrent.locks.ReentrantLock; 7 8 public class ProducerConsumerWithLocks { 9 private static Buffer buffer = new Buffer(); public static void main(String [] args) { 12 ExecutorService executor = Executors.newFixedThreadPool(2); 13 executor.execute(new ProducerTask()); 14 executor.execute(new ConsumerTask()); 15 executor.shutdown(); 16 } private static class ProducerTask implements Runnable { 19 public void run() { 20 try { 21 int i = 1; 22 while (true) { 23 System.out.println("Producer tries to write: " + i); 24 buffer.write(i++); 25 Thread.sleep((int)(Math.random() * 1000)); 26 } 27 } catch (InterruptedException ie) { 28 System.out.println("Producer IE: " + ie.getMessage()); 29 } 30 } 31 } private static class ConsumerTask implements Runnable { 34 public void run() { 35 try { 36 while (true) { 37 System.out.println("\t\tConsumer reads: " + buffer.read()); 38 Thread.sleep((int)(Math.random() * 1000)); 39 } 40 } catch (InterruptedException ie) { 41 System.out.println("Consumer IE: " + ie.getMessage()); 42 } 43 } 44 } USC CSCI 201L6/9 Producer/Consumer 45 private static class Buffer { 46 private static final int CAPACITY = 1; 47 private LinkedList queue = new LinkedList (); 48 private static Lock lock = new ReentrantLock(); 49 private static Condition notEmpty = lock.newCondition(); 50 private static Condition notFull = lock.newCondition(); public void write(int value) { 53 lock.lock(); 54 try { 55 while (queue.size() == CAPACITY) { 56 System.out.println("Wait for notFull condition " + value); 57 notFull.await(); 58 } 59 queue.offer(value); 60 notEmpty.signal(); 61 } catch (InterruptedException ie) { 62 System.out.println("Buffer.write IE: " + ie.getMessage()); 63 } finally { 64 lock.unlock(); 65 } 66 } public int read() { 69 int value = 0; 70 lock.lock(); 71 try { 72 while (queue.isEmpty()) { 73 System.out.println("\t\tWait for notEmpty condition"); 74 notEmpty.await(); 75 } 76 value = queue.remove(); 77 notFull.signal(); 78 } catch (InterruptedException ie) { 79 System.out.println("Buffer.read IE: " + ie.getMessage()); 80 } finally { 81 lock.unlock(); 82 return value; 83 } 84 } 85 } // ends class Buffer 86 } // ends class ProducerConsumerWithLocks

Producer/Consumer Output with Locks/Conditions USC CSCI 201L7/9 Producer/Consumer

Outline USC CSCI 201L8/9 ▪M▪Monitors ▪P▪Program

Program ▪Modify the Producer/Consumer program with locks so that a Producer will never write two lines in a row. Also provide an output line when a Producer or Consumer is notified or signaled. USC CSCI 201L9/9 Program