Click here to Skip to main content
15,878,945 members
Articles / Programming Languages / C#
Article

Thread synchronization: Wait and Pulse demystified

Rate me:
Please Sign up or sign in to vote.
4.83/5 (84 votes)
23 Aug 2008CPOL5 min read 180.5K   148   24
An article on the Wait and Pulse methods of the Monitor class.

Table of Contents

Introduction

This short article is about the three less well understood methods of the Monitor class: Wait, Pulse, and PulseAll. The MSDN documentation for these methods explains what they do, but not why or how to use them. I will try to fill this gap and demystify them.

These methods provide low-level synchronization between threads. They are the most versatile constructs, but they are harder to use correctly than other synchronization primitives like AutoResetEvent. However, if you follow the recommended pattern I will describe, they can be used with confidence.

Basics

C#
public partial static class Monitor
{
  public static bool Wait( object o ) { ... } // and overloads
  public static void Pulse( object o ) { ... }
  public static void PulseAll( object o ) { ... }
}

At the most basic level, a thread calls Wait when it wants to enter a wait state, and another thread calls Pulse when it wants to wake up the waiting thread. Note that if a thread calls Pulse when no other threads are waiting, the Pulse is lost. This is in contrast to primitives like AutoResetEvent, where a call to Set is remembered until a subsequent call to WaitOne occurs.

There is a requirement that all these methods must be called from within a lock statement. If they are called while not holding the lock, then they will throw a SynchronizationLockException. We will see why this is actually useful, later on.

For example:

C#
readonly object key = new object();

// thread A
lock ( key ) Monitor.Wait( key );

// thread B
lock ( key ) Monitor.Pulse( key );

If thread A runs first, it acquires the lock and executes the Wait method. Then, thread B runs, releasing thread A to allow it to continue.

Locks

You may have noticed a little problem with the code above. If thread A holds the lock on the key object, why does thread B not block when it tries to acquire the lock? This is, of course, handled properly. The call to Wait in thread A releases the lock before it waits. This allows thread B to acquire the lock and call Pulse. Thread A then resumes, but it has to wait until thread B releases the lock, so it can reacquire it and complete the Wait call. Note that Pulse never blocks.

simple

Queues

The ready queue is the collection of threads that are waiting for a particular lock. The Monitor.Wait methods introduce another queue: the waiting queue. This is required as waiting for a Pulse is distinct from waiting to acquire a lock. Like the ready queue, the waiting queue is FIFO.

simple

Recommended pattern

These queues can lead to unexpected behaviour. When a Pulse occurs, the head of the waiting queue is released and is added to the ready queue. However, if there are other threads in the ready queue, they will acquire the lock before the thread that was released. This is a problem, because the thread that acquires the lock can alter the state that the pulsed thread relies on.

The solution is to use a while condition inside the lock statement:

C#
readonly object key = new object();
bool block = true;

// thread A
lock ( key )
{
  while ( block )
    Monitor.Wait( key );
  block = true;
}

// thread B
lock ( key )
{
  block = false;
  Monitor.Pulse( key );
}

This pattern shows the reason for the rule that locks must be used: they protect the condition variable from concurrent access. Locks are also memory barriers, so you do not have to declare the condition variables as volatile.

The while loop also solves a couple of other problems. Firstly, if thread B executes before thread A calls Wait, the Pulse is lost. However, when thread A eventually runs and acquires the lock, the first thing it does is check the condition. Thread B has already set block to false, so Thread A continues without ever calling Wait.

Secondly, it solves the problem of the queues. If thread A is pulsed, it leaves the waiting queue and is added to the ready queue. If, however, a different thread acquires the lock and this thread sets block back to true, it now doesn't matter. This is because thread A will go round the while loop, find the condition to block is true, and execute Wait again.

Uses

The code above is actually an implementation of an AutoResetEvent. If you omitted the block = true statement in thread A, it would be a ManualResetEvent. If you use an int instead of bool for the condition, it would be a Semaphore. This shows how versatile this pattern is. You have complete control over what condition you use in the while loop.

So, the rule of thumb is: use higher level primitives if they fit. If you need finer control, use the Monitor methods with this pattern to ensure correctness.

Tips

It is usually okay to use PulseAll instead of Pulse. This causes all the waiting threads to re-evaluate their conditions and either continue or go back to waiting. As long as the condition evaluation is not too expensive, this is normally acceptable. PulseAll is also useful where you have multiple threads waiting on the same synchronization object, but with different conditions.

There are overloads of Wait that take a timeout parameter. Similar to above, this usually doesn't hurt. It can help prevent stuck Waits or missed Pulses by re-evaluating the conditions on a regular basis.

Example

Here is an example with full source code that demonstrates the versatility of this pattern. It implements a blocking queue that can be stopped. A blocking queue is a fixed-size queue. If the queue is full, attempts to add an item will block. If the queue is empty, attempts to remove an item will block. When Quit() is called, the queue is stopped. This means that you can't add any more items, but you can remove existing items until the queue is empty. At that point, the queue is finished.

This is a fairly complex set of conditions. You could implement this using a combination of higher-level constructs, but it would be harder. The pattern makes this implementation relatively trivial.

C#
class BlockingQueue<T>
{
  readonly int _Size = 0;
  readonly Queue<T> _Queue = new Queue<T>();
  readonly object _Key = new object();
  bool _Quit = false;

  public BlockingQueue( int size )
  {
    _Size = size;
  }

  public void Quit()
  {
    lock ( _Key )
    {
      _Quit = true;

      Monitor.PulseAll( _Key );
    }
  }

  public bool Enqueue( T t )
  {
    lock ( _Key )
    {
      while ( !_Quit && _Queue.Count >= _Size ) Monitor.Wait( _Key );

      if ( _Quit ) return false;

      _Queue.Enqueue( t );

      Monitor.PulseAll( _Key );
    }

    return true;
  }

  public bool Dequeue( out T t )
  {
    t = default( T );

    lock ( _Key )
    {
      while ( !_Quit && _Queue.Count == 0 ) Monitor.Wait( _Key );

      if ( _Queue.Count == 0 ) return false;

      t = _Queue.Dequeue();

      Monitor.PulseAll( _Key );
    }

    return true;
  }
}

This implementation is safe for concurrent access by an arbitrary number of producers and consumers. Here is an example with one fast producer and two slow consumers:

C#
internal static void Test()
{
  var q = new BlockingQueue<int>( 4 );

  // Producer
  new Thread( () =>
  {
    for ( int x = 0 ; ; x++ )
    {
      if ( !q.Enqueue( x ) ) break;
      Trace.WriteLine( x.ToString( "0000" ) + " >" );
    }
    Trace.WriteLine( "Producer quitting" );
  } ).Start();

  // Consumers
  for ( int i = 0 ; i < 2 ; i++ )
  {
    new Thread( () =>
    {
      for ( ; ; )
      {
        Thread.Sleep( 100 );
        int x = 0;
        if ( !q.Dequeue( out x ) ) break;
        Trace.WriteLine( "     < " + x.ToString( "0000" ) );
      }
      Trace.WriteLine( "Consumer quitting" );
    } ).Start();
  }

  Thread.Sleep( 1000 );

  Trace.WriteLine( "Quitting" );

  q.Quit();
}

And, here is the output of one run:

0.00000000     0000 >     
0.00006564     0001 >     
0.00009096     0002 >     
0.00011540     0003 >     
0.09100076          < 0000     
0.09105981          < 0001     
0.09118936     0004 >     
0.09121715     0005 >     
0.19127709          < 0002     
0.19138214     0006 >     
0.19141905     0007 >     
0.19156006          < 0003     
0.29184034          < 0004     
0.29195839          < 0005     
0.29209006     0008 >     
0.29211268     0009 >     
0.39240077          < 0006     
0.39249521          < 0007     
0.39265713     0010 >     
0.39268187     0011 >     
0.49300483          < 0008     
0.49308145     0012 >     
0.49310759     0013 >     
0.49324051          < 0009     
0.59353358          < 0010     
0.59361452          < 0011     
0.59378797     0014 >     
0.59381104     0015 >     
0.69410956          < 0012     
0.69421405     0016 >     
0.69423932     0017 >     
0.69443953          < 0013     
0.79467082          < 0014     
0.79478532          < 0015     
0.79493624     0018 >     
0.79496473     0019 >     
0.89524573          < 0016     
0.89536309          < 0017     
0.89549100     0020 >     
0.89552164     0021 >     
0.98704302     Quitting     
0.98829663     Producer quitting     
0.99580252          < 0018     
0.99590403          < 0019     
1.09638131          < 0020     
1.09647286          < 0021     
1.19700873     Consumer quitting     
1.19717586     Consumer quitting

Conclusion

Well, that's about it. I hope I have removed some of the mystery that seems to surround Wait and Pulse, and filled in the gaps left by MSDN.

Thanks for reading this article; I hope you liked it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
I discovered C# and .NET 1.0 Beta 1 in late 2000 and loved them immediately.
I have been writing software professionally in C# ever since

In real life, I have spent 3 years travelling abroad,
I have held a UK Private Pilots Licence for 20 years,
and I am a PADI Divemaster.

I now live near idyllic Bournemouth in England.

I can work 'virtually' anywhere!

Comments and Discussions

 
QuestionProblem with the queue Pin
Member 1374092922-Mar-18 2:11
Member 1374092922-Mar-18 2:11 
GeneralMy vote of 5 Pin
Rajiv Chauhan1-Dec-11 14:49
Rajiv Chauhan1-Dec-11 14:49 
GeneralMy vote of 4 Pin
Sergiy Tkachuk19-Oct-11 13:16
Sergiy Tkachuk19-Oct-11 13:16 
QuestionWhat about ReaderWriterLockSlim Pin
Pedro77k17-Sep-10 12:15
Pedro77k17-Sep-10 12:15 
GeneralMy vote of 5 Pin
noshirwan1-Sep-10 9:12
noshirwan1-Sep-10 9:12 
GeneralIt’s really “demystifying” :) Pin
emre200826-Sep-09 8:05
emre200826-Sep-09 8:05 
GeneralRe: It’s really “demystifying” :) Pin
Nicholas Butler27-Sep-09 1:19
sitebuilderNicholas Butler27-Sep-09 1:19 
Generalvery useful Pin
Dong Xiang28-Jul-09 10:25
Dong Xiang28-Jul-09 10:25 
GeneralRe: very useful Pin
Nicholas Butler28-Jul-09 10:39
sitebuilderNicholas Butler28-Jul-09 10:39 
GeneralExactly what I was looking for! Pin
rony96-May-09 2:50
rony96-May-09 2:50 
GeneralEquivalent of WaitHandle.WaitAll Pin
Dmitri Nеstеruk27-Nov-08 3:30
Dmitri Nеstеruk27-Nov-08 3:30 
AnswerRe: Equivalent of WaitHandle.WaitAll Pin
Nicholas Butler27-Nov-08 11:25
sitebuilderNicholas Butler27-Nov-08 11:25 
GeneralRe: Equivalent of WaitHandle.WaitAll Pin
supercat97-Jul-09 5:53
supercat97-Jul-09 5:53 
GeneralLock free Blocking queue Pin
Saar Yahalom29-Aug-08 0:21
Saar Yahalom29-Aug-08 0:21 
GeneralRe: Lock free Blocking queue Pin
Nicholas Butler29-Aug-08 2:26
sitebuilderNicholas Butler29-Aug-08 2:26 
GeneralVery very good sir Pin
Sacha Barber25-Aug-08 22:15
Sacha Barber25-Aug-08 22:15 
GeneralRe: Very very good sir Pin
Nicholas Butler26-Aug-08 4:56
sitebuilderNicholas Butler26-Aug-08 4:56 
GeneralRe: Very very good sir Pin
Sacha Barber26-Aug-08 5:00
Sacha Barber26-Aug-08 5:00 
GeneralRe: Very very good sir Pin
Nicholas Butler26-Aug-08 5:05
sitebuilderNicholas Butler26-Aug-08 5:05 
GeneralRe: Very very good sir Pin
Sacha Barber26-Aug-08 5:52
Sacha Barber26-Aug-08 5:52 
GeneralGood stuff Pin
MR_SAM_PIPER25-Aug-08 14:01
MR_SAM_PIPER25-Aug-08 14:01 
GeneralRe: Good stuff Pin
Nicholas Butler26-Aug-08 4:54
sitebuilderNicholas Butler26-Aug-08 4:54 
GeneralGreat article! Pin
rht34124-Aug-08 5:50
rht34124-Aug-08 5:50 
GeneralRe: Great article! Pin
Nicholas Butler24-Aug-08 7:34
sitebuilderNicholas Butler24-Aug-08 7:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.