Synchronization Monitors for Win32 
by Thomas Becker

Example 1: 

FairMonitor::Wait()
{
  create a Win32 event
  [place the event handle in the wait set]
  release the lock
  block on the event
  acquire the lock
  destroy the event
}
FairMonitor::Notify()
{
  [retrieve and remove the oldest event handle from the wait set]
  set the event to the signaled state
}
FairMonitor::NotifyAll()
{
  [retrieve and remove all event handles from the wait set]
  set all events to the signaled state
}

Listing One
Interface to generic Win32 monitor class
class Monitor
{
public:
  // Default constructor.
  Monitor();
  // Destructor
  ~Monitor();
  // Aquires the lock.
  void BeginSynchronized();
  // Releases the lock.
  void EndSynchronized();
  // Waits for a notification.
  DWORD Wait(DWORD dwMillisecondsTimeout = INFINITE);
  // Notifies one of the waiting threads, if any.
  BOOL Notify();
  // Notifies all of the waiting threads, if any.
  BOOL NotifyAll();
  private:
  // ...
};

Listing Two
Reader-writer lock pseudocode
ReadWriteLock::EnterRead()
{
  acquire monitor lock;
  while( 0 < m_nNumberOfWaitingWriters || m_bWriteInProgress ) {
    wait in monitor's reader set;
  }
  ++m_nNumberOfActiveReaders;
  release monitor lock;
}
ReadWriteLock::LeaveRead()
{
  acquire monitor lock;
  if( 0 == --m_nNumberOfActiveReaders ) {
    notify on monitor's writer set;
  }
  release monitor lock;
}
ReadWriteLock::EnterWrite()
{
  acquire monitor lock;
  ++m_nNumberOfWaitingWriters;
  while( 0 < m_nNumberOfActiveReaders || m_bWriteInProgress ) {
    wait in monitor's writer set;
  }
  --m_nNumberOfWaitingWriters;
  m_bWriteInProgress = true;
  release monitor lock;
}
ReadWriteLock::LeaveWrite()
{
  acquire monitor lock;
  m_bWriteInProgress = false;
  if( 0 == m_nNumberOfWaitingWriters ) {
    notify-all on monitor's reader set;
  }
  else {
    notify on monitor's writer set;
  }
   release monitor lock;
}



2

