CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Similar documents
CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

CMSC 330: Organization of Programming Languages

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

CMSC 132: Object-Oriented Programming II. Threads in Java

Synchronized Methods of Old Versions of Java

CMSC 330: Organization of Programming Languages. Concurrency & Multiprocessing

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 32 Multithreading and Parallel Programming

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

Chapter 6: Process Synchronization

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

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

CS193k, Stanford Handout #8. Threads 3

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Only one thread can own a specific monitor

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014

G52CON: Concepts of Concurrency

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

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Synchronization in Java

Java ReentrantLock (Part 1)

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

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

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

Models of concurrency & synchronization algorithms

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

Chapter 6: Process Synchronization

Synchronization in Concurrent Programming. Amit Gupta

CS 537 Lecture 8 Monitors. Thread Join with Semaphores. Dining Philosophers. Parent thread. Child thread. Michael Swift

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

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

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

CS 10: Problem solving via Object Oriented Programming Winter 2017

Process Management And Synchronization

Advanced Concepts of Programming

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Process Synchronization

Process Synchronization

Dr.-Ing. Michael Eichberg

Threads Questions Important Questions

Synchronization problems with semaphores

Chapter 7: Process Synchronization!

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Lesson 6: Process Synchronization

Java Threads. COMP 585 Noteset #2 1

Introduction to Java Threads

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

Synchronization Principles

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

RACE CONDITIONS AND SYNCHRONIZATION

CS11 Java. Fall Lecture 7

Java Programming Lecture 23

Concurrency in Java Prof. Stephen A. Edwards

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

JFokus Finding And Solving Java Deadlocks

Threads, Concurrency, and Parallelism

Dr.-Ing. Michael Eichberg

Programming Languages

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

Interprocess Communication By: Kaushik Vaghani

Concurrent Programming Benoît Garbinato

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

CHAPTER 6: PROCESS SYNCHRONIZATION

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Concurrency: Deadlock and Starvation. Chapter 6

COMP 322: Fundamentals of Parallel Programming

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition

CS3502 OPERATING SYSTEMS

Concurrency in Object Oriented Programs 3. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Concurrent Programming using Threads

Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1

SFDV3006 Concurrent Programming

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

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

PROCESS SYNCHRONIZATION

Process Synchronization

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

CSCC 69H3 2/1/13. Today: Deadlock. Remember example from last week? Example of Deadlock. Example: dining philosophers: Not just an OS Problem!

3C03 Concurrency: Starvation and Deadlocks

Principles of Software Construction: Concurrency, Part 2

Programming Language Concepts: Lecture 11

5. Liveness and Guarded Methods

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - XI Deadlocks - II. Louisiana State University

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

What's wrong with Semaphores?

Dealing with Issues for Interprocess Communication

Concurrency. Chapter 5

CS 111. Operating Systems Peter Reiher

Transcription:

: Organization of Programming Languages Threads Classic Concurrency Problems

The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either side of their plate No talking! Avoid deadlock and starvation! 2

Bad Dining Philosophers Solution 1 Philosophers all pick up the left fork first Deadlock! all are holding the left fork and waiting for the right fork 3

Bad Dining Philosophers Solution 2 Philosophers all pick up the left fork first Philosophers put down a fork after waiting for 5 minutes, then wait 5 minutes before picking it up again Starvation! 4

Possible Solutions The waiter solution Third party arbiter (scheduler) Each thread requests permission before acquiring a resource The resource hierarchy solution Impose ordering on resources Must obtain resources in order Most practical solution Sometimes hard to know in advance 5

Dining Philosophers Solution try u o y! Number the philosophers Start by giving the fork to the philosopher with lower number. Initially, all forks are dirty. When a philosopher wants both forks, he sends a message to his neighbors When a philosopher with a fork receives a message: if his fork is clean, he keeps it, otherwise he cleans it and gives it up. After a philosopher eats, his forks are dirty. If a philosopher had requested his fork, he cleans it and sends it. 6

Dining Philosophers Example 2 1 3 Each philosopher begins with the forks shown. All are dirty. 5 4 7

Dining Philosophers Example 2 1 3 Philosopher 2 sends a message to philosopher 1 that he wants his fork. Their shared fork is dirty, so philosopher 1 cleans it and sends it. 5 4 8

Dining Philosophers Example 2 1 3 Philosopher 2 eats! While he is eating philosopher 3 requests their shared fork. 5 4 Philosopher 2 is done eating, so his forks become dirty. 9

Dining Philosophers Example 2 1 3 Philosopher 2 is done eating, so he honors philosopher 3 s request and cleans the fork and sends it. Philosopher 3 eats! 5 4 10

Philosophers Implementation Needs Wait until notified about something by another philosopher stay hungry until you have two forks hold onto your fork until your neighbor needs it Send a message to a philosopher and have it processed at a later time multiple philosophers can send messages to one when philosopher done eating he should process all and here s another problem with these needs 11

Producer/Consumer Problem Suppose we are communicating with a shared variable E.g., some kind of a fixed size buffer holding messages One thread produces input to the buffer One thread consumes data from the buffer Rules: producer can t add input to the buffer if it s full consumer can t take input from the buffer if it s empty 12

Producer / Consumer Idea If the buffer is partially full, producer or consumer can run: c producer b a consumer If the buffer is empty, only the producer can run: producer If the buffer is full, only the consumer can run: e d c b a consumer 13

Needed Solution Need a way of having threads wait on a resource Also need a way to notify waiting threads when they can wake up Java 1.5 provides a very robust Condition mechanism to fill these needs Slides are included for self-study However, Java 1.4 provided a simpler mechanism that we will discuss 14

Conditions (Java 1.5) interface Lock { Condition newcondition();... } interface Condition { void await(); void signalall();... } Condition created from a Lock await called with lock held Releases the lock (on the fork or buffer) But not any other locks held by this thread Condition... Adds this thread to wait set for lock Blocks the thread when philosopher is waiting for a fork or consumer is waiting for non empty buffer wait set 15

Conditions (Java 1.5) interface Lock { Condition newcondition();... } interface Condition { void await(); void signalall();... } Condition created from a Lock when philosopher is done eating or when buffer is non empty: Condition... signallall called with lock held Resumes all threads on lock s wait set Those threads must reacquire lock before continuing (This is part of the function; you don t need to do it explicitly) wait set 16

Producer/Consumer Example Lock lock = new ReentrantLock(); Condition ready = lock.newcondition(); boolean bufferready = false; Object buffer; void produce(object o) { lock.lock(); while (bufferready){ ready.await(); } buffer = o; bufferready = true; ready.signalall(); lock.unlock(); } Object consume() { lock.lock(); while (!bufferready){ ready.await(); } Object o = buffer; bufferready = false; ready.signalall(); lock.unlock(); } 17

Use This Design This is the right solution to the problem Tempting to try to just use locks directly Very hard to get right Problems with other approaches often very subtle here are a few bad solutions 18

Broken Producer/Consumer Example Lock lock = new ReentrantLock(); boolean valueready = false; Object value; void produce(object o) { lock.lock(); while (valueready); value = o; valueready = true; lock.unlock(); } Object consume() { lock.lock(); while (!valueready); Object o = value; valueready = false; lock.unlock(); } Threads wait with lock held no way to make progress 19

Broken Producer/Consumer Example Lock lock = new ReentrantLock(); boolean valueready = false; Object value; void produce(object o) { while (valueready); lock.lock(); value = o; valueready = true; lock.unlock(); } Object consume() { while (!valueready); lock.lock(); Object o = value; valueready = false; lock.unlock(); } valueready accessed without a lock held race condition 20

Broken Producer/Consumer Example Lock lock = new ReentrantLock(); Condition ready = lock.newcondition(); boolean valueready = false; Object value; void produce(object o) { lock.lock(); if (valueready) ready.await(); value = o; valueready = true; ready.signalall(); lock.unlock(); } Object consume() { lock.lock(); if (!valueready) ready.await(); Object o = value; valueready = false; ready.signalall(); lock.unlock(); } what if there are multiple producers or consumers? 21

Why was it broken? Suppose you have 2 consumers, 1 producer Producer starts. valueready set to true. Both consumers exit while loop and try to aquire lock. One consumer gets the lock and consumes the input. The next consumer is still able to get the lock. ERROR! 22

More on the Condition Interface interface Condition { void await(); boolean await (long time, TimeUnit unit); void signal(); void signalall();... } await(t, u) waits for time t and then gives up Result indicates whether woken by signal or timeout signal() wakes up only one waiting thread Tricky to use correctly Have all waiters be equal, handle exceptions correctly Highly recommended to just use signalall() 23

Await and SignalAll Gotcha s await must be in a loop Don t assume that when wait returns conditions are met Avoid holding other locks when waiting await only gives up locks on the object you wait on 24

Wait and NotifyAll (Java 1.4) Recall that in Java 1.4, use synchronize on object to get associated lock o s lock object o o s wait set Objects also have an associated wait set 25

Wait and NotifyAll (cont d) o.wait() (same as await) Must hold lock associated with o Release that lock And no other locks Adds this thread to wait set for lock Blocks the thread o.notifyall() (same as signalall) Must hold lock associated with o Resumes all threads on lock s wait set Those threads must reacquire lock before continuing (This is part of the function; you don t need to do it explicitly) 26

Producer/Consumer in Java 1.4 public class ProducerConsumer { private boolean valueready = false; private Object value; synchronized void produce(object o) { while (valueready) wait(); value = o; valueready = true; notifyall(); } } synchronized Object consume() { while (!valueready) wait(); valueready = false; Object o = value; notifyall(); return o; } synchronizes on lock for this waits using lock and wait set for this 27

Aspects of Synchronization Atomicity Locking to obtain mutual exclusion What we most often think about Visibility Ensuring that changes to object fields made in one thread are seen in other threads Ordering Ensuring that you aren t surprised by the order in which statements are executed 28

Guidelines for Programming w/threads Synchronize access to shared data Don t hold multiple locks at a time Could cause deadlock Hold a lock for as little time as possible Reduces blocking waiting for locks While holding a lock, don t call a method you don t understand E.g., a method provided by someone else, especially if you can t be sure what it locks Corollary: document which locks a method acquires 29

Thread Cancellation Example scenarios: want to cancel thread Whose processing the user no longer needs (i.e., she has hit the cancel button) That computes a partial result and other threads have encountered errors, etc. Java used to have Thread.kill() But it and Thread.stop() are deprecated Use Thread.interrupt() instead 30

Why No Thread.kill()? What if the thread is holding a lock when it is killed? The system could Free the lock, but the data structure it is protecting might be now inconsistent Keep the lock, but this could lead to deadlock A thread needs to perform its own cleanup Use InterruptedException and isinterrupted() to discover when it should cancel 31

Thread.interrupt() Tries to wake up a thread Sets the thread s interrupted flag Flag can be tested by calling interrupted() method Static, and clears the interrupt flag isinterrupted() method Instance, and does not clear the interrupt flag Won t disturb the thread if it is working Not asynchronous! 32

Cancellation Example public class CancellableReader extends Thread { private FileInputStream datafile; public void run() { try { while (!Thread.interrupted()) { This could acquire try { locks, be on a wait int c = datafile.read(); if (c == -1) break; set, etc. else process(c); } catch (IOException ex) { break; } } } finally { // cleanup here } } } What if the thread is blocked on a lock or wait set, or sleeping when interrupted? 33

InterruptedException Exception thrown if interrupted on certain ops wait, await, sleep, join, and lockinterruptibly Also thrown if call one of these with interrupt flag set 34

Responses to Interruption Early Return Clean up and exit without producing errors May require rollback or recovery Continuation (i.e., ignore interruption) When it is too dangerous to stop When partial actions cannot be backed out When it doesn t matter 35

Responses to Interruption (cont d) Re-throw InterruptedException When callers must be alerted on method return Throw a general failure exception When interruption is a reason method may fail In general Must reset invariants before cancelling E.g., close file descriptors, notify other waiters, etc. 36

Handling InterruptedException synchronized (this) { while (!ready) { try { wait(); } catch (InterruptedException e) { // make shared state acceptable notifyall(); // cancel processing return; } // do whatever } } 37