Threads II: Synchronization
Tom Kelliher, CS 245
Oct. 13, 2008
Wednesday: Deliverables, Exam I.
Friday: Read Chapter 6.
Introduction to threads.
- Thread Synchronization
- Lab
Exam I, Game2D case study.
- The Producer/Consumer problem:
- Producer and Consumer work at different rates.
- Fixed amount of buffering (queuing) between them.
- With no synchronization, items can ``disappear'' or be multiply
consumed.
- A solution: the monitor.
- Lock and condition variables.
- A thread must secure the lock before executing within the
monitor.
- Once in the monitor, a thread checks its condition variables:
- Producer: queue full.
- Consumer: queue empty.
If the condition is false, the thread waits -- exits the monitor and
sleeps. When it awakes, it must recheck its condition.
- Once a thread has modified state within the monitor, it will
notify waiting threads, allowing them to recheck their conditions.
(Must first re-obtain lock.)
- Example:
class Queue
{
private int val;
private boolean full = false;
private boolean empty = true;
public Queue()
{
val = 0;
}
public synchronized void put(int v)
{
while (full)
try
{
wait();
}
catch (Exception e)
{
}
val = v;
full = true;
empty = false;
notify();
}
public synchronized int get()
{
while (empty)
try
{
wait();
}
catch (Exception e)
{
}
full = false;
empty = true;
notify();
return val;
}
}
Thomas P. Kelliher
2008-10-10
Tom Kelliher