Lecture Notes for Concurrent Programming

30 July 2002 - Synchronization Utilities


Synchronization Utilities


Semaphores


Semaphore Implementation

 
 class Semaphore

   private Mutex mtx(false), waitq(false)
   private int count, waiters = 0

   Semaphore(int count) { this.count = count }

   void down() throws InterruptedException
     mtx.lock()

     while count < 1
       waiters++
       mtx.unlock()

       try { waitq.lock() }
       catch (InterruptedException ie)
	 synchronized (this) { waiters-- } ; throw ie 

       try mtx.lock()
       catch (InterruptedException ie)
	 synchronized (this) { waiters-- } ; throw ie 
       waiters--

     count--
     mtx.unlock()

   void up()
     try mtx.lock()
     catch (InterruptedException ie) return
     count++
     if (waiters > 0) waitq.unlock()
     mtx.unlock()
 


Latches


Latch Implementation

 class Latch

   // Invariant:  ready implies the wait set is empty.

   private boolean ready = false

   synchronized void block() 
   throws InterruptedException
     try { while (!ready) wait() }
     catch (InterruptedException ie) 
       throw ie

   void unblock()
     if !ready
       ready = true
       notifyAll()


Exchangers


Exchanger Implementation


 class Exchanger

   private Object fst, snd
   private boolean interrupted = false

   synchronized Object exchange(Object o) 
   throws InterruptedException

     if interrupted
       interrupted = false
       throw new InterruptedException()

     if fst != null
       snd = o
       notify()
       return fst

     fst = o
     try { while (snd == null) wait() }
     catch (InterruptedException ie)
       fst = null
       interrupted = true
       throw ie

     return snd


Single Wait Sets


Condition Variables


Condition Variable Example


Condition Variable Implementation

 public class ConditionVariable

   public void pause() throws InterruptedException

     if Thread.interrupted() 
       throw new InterruptedException()

     try
       synchronized this
	 mutex.unlock()  // It's locked coming in.
	 try wait() 
	 catch (InterruptedException ex)
	   notify()
	   throw ex
     finally
       boolean interrupted = false
       while true
	 try
	   mutex.lock()
	   break
	 catch (InterruptedException ex)
	   interrupted = true
       if interrupted
	 Thread.currentThread().interrupt()

   public synchronized void proceed()
     notify()


Points to Remember


This page last modified on 8 August 2002.