title: How implement a barrier using semaphores
body: <p>I have the following problem to solve:</p>
  
  <p><em>Consider an application where there are three types of threads: Calculus-A,Calculus-B and Finalization. Whenever a thread type Calculus-A ends, it calls the routine endA(), which returns  immediately. Whenever a thread type Calculus-B ends, it calls the routine endB(), which returns immediately. Threads like Finalization routine call wait(),
  which returns only if they have already completed two Calculation-A threads and 2 Calculation-B threads. In other words, for exactly 2 conclusions of Calculus-A and 2 conclusions of Calculus-B one thread Finalization is allowed to continue.
  There is an undetermined number of threads of the 3 types. It is not known the order of the routines called by threads. Threads Completion are answered in the order of arrival.
  Implement routines endA(), endB() and wait() using semaphores. Besides the variables initialization, the only possible operations are P and V. Solutions with busy-waiting are not acceptable.</em></p>
  
  <p>Here's is my solution:</p>
  
  <pre><code>semaphore calcA = 2;
  semaphore calcB = 2;
  semaphore wait = -3;
  
  void endA()
      {
          P(calcA);
          V(wait);
      }
  
  void endB()
      {
          P(calcB);
          V(wait);
      }
  
  void wait()
      {
          P(wait);
          P(wait);
          P(wait);
          P(wait);
          V(calcA);
          V(calcA);
          V(calcB);
          V(calcB);
      }
  </code></pre>
  
  <p>I believe that there will be a deadlock due to the wait's initialization and if and wait() executes before endA() and endB(). Is there any other solution for this?</p>