Threads II: Synchronization

Tom Kelliher, CS 245

Oct. 13, 2008

Administrivia

Announcements

Assignment

Wednesday: Deliverables, Exam I.

Friday: Read Chapter 6.

From Last Time

Introduction to threads.

Outline

  1. Thread Synchronization

  2. Lab

Coming Up

Exam I, Game2D case study.

Thread Synchronization

  1. The Producer/Consumer problem:

    \includegraphics{Figures/prodCons.eps}

    1. Producer and Consumer work at different rates.

    2. Fixed amount of buffering (queuing) between them.

    3. With no synchronization, items can ``disappear'' or be multiply consumed.

  2. A solution: the monitor.

    1. Lock and condition variables.

    2. A thread must secure the lock before executing within the monitor.

    3. Once in the monitor, a thread checks its condition variables:
      1. Producer: queue full.

      2. Consumer: queue empty.

      If the condition is false, the thread waits -- exits the monitor and sleeps. When it awakes, it must recheck its condition.

    4. 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.)

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

Lab



Thomas P. Kelliher 2008-10-10
Tom Kelliher