Docsity

Concurrent Programming: Dining Philosophers and Producer-Consumer Problems, Study notes of Programming Languages

Partial preview of the text

Download Concurrent Programming: Dining Philosophers and Producer-Consumer Problems and more Study notes Programming Languages in PDF only on Docsity!

CMSC 330: Organization of

Programming Languages

Threads

Classic Concurrency Problems

CMSC 330 2

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

• Avoid deadlock and

starvation!

CMSC 330 3

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

CMSC 330 4

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!

CMSC 330 7

Dining Philosophers Example

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.

CMSC 330 8

Dining Philosophers Example

Philosopher 2 eats!

While he is eating

philosopher 3

requests their shared

fork.

Philosopher 2 is done

eating, so his forks

become dirty.

CMSC 330 9

Dining Philosophers Example

Philosopher 2 is done

eating, so he honors

philosopher 3’s

request and cleans

the fork and sends it.

Philosopher 3 eats!

CMSC 330 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…

CMSC 330 13

Pseudocode Solution

• How can we solve this problem using one

thread for the producer and one for the

consumer?

  • no deadlock
  • no data races

you try!

CMSC 330 14

Conditions (Java 1.5)

  • 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
    • 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

interface Lock { Condition newCondition(); ... } interface Condition { void await(); void signalAll(); ... }

Condition

wait set

CMSC 330 15

Conditions (Java 1.5)

  • Condition created from a Lock

when philosopher is done eating or when buffer is non empty:

  • 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)

interface Lock { Condition newCondition(); ... } interface Condition { void await(); void signalAll(); ... }

Condition

wait set

CMSC 330 16

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(); }

Producer/Consumer Example

CMSC 330 19

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(); }

Broken Producer/Consumer Example

valueReady accessed without a lock held – race condition

CMSC 330 20

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(); }

Broken Producer/Consumer Example

what if there are multiple producers or consumers?

CMSC 330 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!

CMSC 330 22

More on the Condition Interface

• away(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()

interface Condition { void await(); boolean await (long time, TimeUnit unit); void signal(); void signalAll(); ... }

CMSC 330 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)

CMSC 330 26

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; } }

Producer/Consumer in Java 1.

synchronizes

on lock for this

waits using

lock and wait

set for this

CMSC 330 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

CMSC 330 28

Quiz

• Can this result in i=0 and j=0?

CMSC 330 31

When Are Actions Visible?

Must be the same lock

CMSC 330 32

Forcing Visibility of Actions

• All writes from thread that holds lock M are

visible to next thread that acquires lock M

  • Must be the same lock

• Use synchronization to enforce visibility and

ordering

  • As well as mutual exclusion

CMSC 330 33

Volatile Fields

• Fields which are visible immediately across all

threads

• If you are going to access a shared field without

using synchronization

  • It needs to be volatile

• Example uses

  • A one-writer/many-reader value
    • Simple control flags:
      • volatile boolean done = false;
  • Keeping track of a “recent value” of something

CMSC 330 34

Misusing Volatile

• Incrementing a volatile field can cause a data

race (just as for any other field)

• A volatile reference to an object isn’t the same

as having the fields of that object be volatile

  • No way to make elements of an array volatile

• Can’t keep two volatile fields in sync

• Don’t use for this course

CMSC 330 37

Thread.interrupt()

• Tries to wake up a thread

  • Sets the thread’s interrupted flag
  • Flag can be tested by calling
    • interrupted() method
      • Clears the interrupt flag
    • isInterrupted() method
      • Does not clear the interrupt flag

• Won’t disturb the thread if it is working

  • Not asynchronous!

CMSC 330 38

Cancellation Example

public class CancellableReader extends Thread { private FileInputStream dataFile; public void run() { try { while (!Thread.interrupted()) { try { int c = dataFile.read(); if (c == -1) break; 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?

This could acquire

locks, be on a wait

set, etc.

CMSC 330 39

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

• Not thrown when blocked on 1.4 lock or I/O

class Object { void wait() throws IE; ... } interface Lock { void lock(); void lockInterruptibly() throws IE; ... } interface Condition { void await() throws IE; void signalAll(); ... }

CMSC 330 40

Responses to Interruption

• Early Return

  • Clean up and exit without producing errors
  • May require rollback or recovery
  • Callers can poll cancellation status to find out why an

action was not carried out

• Continuation (i.e., ignore interruption)

  • When it is too dangerous to stop
  • When partial actions cannot be backed out
  • When it doesn’t matter