title: C++ Semaphore and pthreads behaving indeterminately
body: <p>my professor has given us a code example to examine over the weekend. A code example which he says compiles and runs however I can't run it and reproduce the desired behavior. The program is supposed to run and print out a 1 on the first line and a 2 on the second line. Instead it behaves indeterminately sometimes putting 12 or 21 or even the desired output. What's going on here? I'm compiling on OSX mavericks.</p>
  
  <pre><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;semaphore.h&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  sem_t mySemaphore;
  
  void *f1(void *param)
  {
          cout &lt;&lt; (long)param &lt;&lt; std::endl;
  
          // signal semaphore
          // increment the value of mySemaphore by 1
          // if there are one or more threads waiting, wake
          sem_post(&amp;mySemaphore);
  
          pthread_exit(NULL);
  }
  
  void *f2(void *param)
  {
          // wait until value of semaphore is greater than 0
          // decrement the value of semaphore by 1
          sem_wait(&amp;mySemaphore);
  
          cout &lt;&lt; (long)param &lt;&lt; std::endl;
  
          pthread_exit(NULL);
  }
  
  int main()
  {
          pthread_t myThread[2];
  
          // The 3rd value which is semaphore count set to 0
          sem_init(&amp;mySemaphore, 0, 0);
  
          long one = 1, two = 2;
  
          // f2 has sem_wait(), so it should wait
          // until f1 increase the semaphore value to 1
          // As a result, f1 will be executed first
          pthread_create(&amp;myThread[0], 0, f1, (void *)one);
          pthread_create(&amp;myThread[1], 0, f2, (void *)two);
  
          pthread_join(myThread[0], 0);
          pthread_join(myThread[1], 0);
          sem_destroy(&amp;mySemaphore);
          return 0;
  }
  </code></pre>