title: Producer-Consumer example, both in lock(this) block
body: <p>I was looking at Example 2 on this <a href="http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx" rel="nofollow">msdn</a> page about Thread synchronization with Monitor.Pulse().</p>
  
  <p>A Cell object is created and passed to both the producer and the consumer objects. </p>
  
  <pre><code>Cell cell = new Cell( );
  CellProd prod = new CellProd(cell, 20);
  CellCons cons = new CellCons(cell, 20);
  </code></pre>
  
  <p>A thread is created for each of those two</p>
  
  <pre><code>Thread producer = new Thread(new ThreadStart(prod.ThreadRun));
  Thread consumer = new Thread(new ThreadStart(cons.ThreadRun));
  </code></pre>
  
  <p>The ThreadRun in each case being a loop that calls Cell.ReadFromCell() or Cell.WriteToCell() depending on consumer/producer. For example, the producer does this</p>
  
  <pre><code>public void ThreadRun( )
  {
    for(int looper=1; looper&lt;=quantity; looper++)
       cell.WriteToCell(looper);  // "producing"
  }
  </code></pre>
  
  <p>The bit I don't understand is that in each of these methods they start with a</p>
  
  <pre><code>lock(this)
  </code></pre>
  
  <p>And since it was the same Cell object (ie, the 'this' in the above lock statement) passed to both, I would have thought that only one thread could be in this section of code at a time. Yet from Monitor.Pulse() and Monitor.Wait() code that follows it looks like both threads are in those sections at the same time. If one had the lock and hit a Monitor.Wait() then the other thread could never Pulse because it is blocked waiting for the lock.</p>
  
  <p>I'm guessing there is a simple solution and I have misunderstood something, from my tests with running the code it looks like both threads are in their critical sections at the same time, so the lock(this) isn't doing what I was under the impression it should do.</p>