title: Condition Variable - Wait/Notify Race Condition
body: <p>I'll present some code first since explaining is easier that way. Assume that mutexes are correctly used with the condition variables to keep it simple:</p>
  
  <pre><code>// Thread 1
  while(1)
  {
      conditionVariable.wait();
      // Do some work
  }
  
  // Thread 2
  while(1)
  {
      // Do some work
      conditionVariable.notify_one();
  }
  
  // Thread 3
  while(1)
  {
      // Do some work
      conditionVariable.notify_one();
  }
  </code></pre>
  
  <p>What I would like to achieve is that thread 1 is guaranteed to be waiting on the condition variable when thread 2 or Thread 3 notifies. As the code stands, there is a large gap between <code>notify_one()</code> and <code>wait()</code> in the form of some other code marked by the comments. This gap means sometimes <code>notify_one()</code> is called before gets a chance to call <code>wait()</code>.</p>
  
  <p>After some thought it seems that the closest I can get to this is to use some form of mutual exclusion before <code>notify_one()</code> and before <code>wait()</code> (at the start of thread 1's loop). However, no matter how this is done, there is still a small gap (1 line of code) between the mutual exclusion and the <code>wait()</code>, allowing Threads 2 and 3 to call <code>notify_one()</code> just before Thread 1 calls <code>wait()</code>. It's unlikely, but possible.</p>
  
  <p>I also thought about using the <code>wait()</code> predicate to flag a boolean allowing the other threads to notify. I guess this would work since <code>wait()</code> is atomic, but I'm wondering if there is a better way. Perhaps I am approaching this incorrectly.</p>
  
  <p>In summary: how can I ensure thread 1 is waiting before allowing threads 2 and 3 to notify?  </p>