title: an example on thread synchronization using semaphore
body: <p>I'm having a hard time working on process synchronization with semaphore. Basically, I failed to see how interruption could disrupt the program, and construct scenarios to issue the problem. Below is a problem I've stuck for a few days. Please help out. Thanks in advance!</p>
  
  <p>Description: The “H2O” problem.</p>
  
  <p>hReady() and oReady() are functions "generating" H and O. Each H thread and O thread executes hReady() and oReady(). Upon ready of TWO H and ONE O, one of the procedure must call makewater(). Solution should avoid starvation and busy-waiting. Also assuming FIFO policy for thread wake-ups.</p>
  
  <p>Approach 1: Any problem in this approach? (Answer is Yes. And I can understand why.)</p>
  
  <pre><code>int numHydrogen = 0; 
  sema_t pairOfHydrogen = 0; 
  sema_t oxygen = 0; 
  
  void hReady() { 
      numHydrogen ++;                // I'm assuming here should have a mutex
      if ((numHydrogen % 2) == 0) { 
      signal(pairOfHydrogen); 
      } 
      wait(oxygen); 
  } 
  
  void oReady() { 
      wait(pairOfHydrogen); 
      makeWater(); 
      signal(oxygen); 
      signal(oxygen); 
  } 
  </code></pre>
  
  <p>Approach 2: Any problem? (Answer is Yes. But I'm not quite sure why. Also how to construct a specific scenario?)</p>
  
  <pre><code>sema_t hPresent = 0; 
  sema_t waitForWater = 0; 
  
  void hReady() { 
      signal(hPresent); 
      wait(waitForWater); 
  } 
  
  void oReady() { 
      wait(hPresent);       // It seems something wrong here. I'm not sure why
      wait(hPresent);       // Also here. Why?
      makeWater(); 
      signal(waitForWater); 
      signal(waitForWater); 
  }
  </code></pre>
  
  <p>Approach 3: Assuming LIFO for thread wake-ups in approach 2. Any problem? 
  (Also Yes. But why? How wake-up policy comes to part of the play in this question? )</p>
  
  <p>Is there any easy way to sort out similar questions? And how should one think about constructing a scenario? Again, thanks for any help!</p>