title: How exactly does the wait function work (in regards to condition variables)
body: <p>I am a little bit confused on my understanding of how condition variables work (in regards to shared data concurrent access)</p>
  
  <p>The following is pseudo C code to illustrate my current problem</p>
  
  <pre><code>// Thread 1: Producer
  void cakeMaker()
  {
      lock(some_lock);
      while(number_of_cakes == MAX_CAKES)
          wait(rack_has_space);
  
      number_of_cakes++;
  
      signal(rack_has_cakes);
      unlock(some_lock);
  }
  
  // Thread 2: Consumer
  void cakeEater()
  {
      lock(some_lock);
      while(number_of_cakes == 0)
          wait(rack_has_cakes);
  
      number_of_cakes--;
  
      signal(rack_has_space);
      unlock(some_lock);
  }
  </code></pre>
  
  <p>Lets say we currently have <code>number_of_cakes = 0</code>, so <code>Thread 2</code> is currently stuck on <code>wait(rack_has_cakes)</code>. <code>Thread 1</code> runs and increments <code>number_of_cakes</code> by 1. Then it calls <code>signal(rack_has_cakes)</code> - this wakes up <code>Thread 2</code>, unfortunately <code>Thread 2</code> wakes up before <code>Thread 1</code> calls <code>unlock(some_lock)</code>, so it goes back to sleep again and the signal has been missed.</p>
  
  <p>I am very confused about the inner workings of <code>wait</code> and <code>signal</code>? What exactly happens with them? Are they like some boolean flag that gets automatically set to 1 when we call signal and set to 0 again when wait succeeds? What is going on?</p>
  
  <h3>Can someone run me through step by step 1 iteration of the above code, heavy emphasis on what happens during signal and wait?</h3>