title: Implementing a binary semaphore class in C++
body: <p>So, I am working on a scheduler in one of my classes. Basically, we are pretending that only one thread can be executing at a time. We are supposed to use a semaphore class to allow these threads to block themselves to simulate the thread waiting for the CPU. </p>
  
  <p>The problem is, the threads seem to block at the wrong time and execute at the wrong time. I was wondering if I am missing some conceptual understanding of a semaphore and how to implement it. I was wondering if I could get some feedback on my implementation. The instructor provided this header file which I have not modified in any way:</p>
  
  <pre><code>class Semaphore {
  private:
    int             value;
    pthread_mutex_t m;
    pthread_cond_t  c;
  
  public:
  
    /* -- CONSTRUCTOR/DESTRUCTOR */
  
    Semaphore(int _val);
  
    //~Semaphore();
  
    /* -- SEMAPHORE OPERATIONS */
  
    int P();
    int V();
  };
  </code></pre>
  
  <p>This is my implementation using posix stuff:</p>
  
  <pre><code>Semaphore::Semaphore(int _val){
      value = _val;
      c = PTHREAD_COND_INITIALIZER;
      m = PTHREAD_MUTEX_INITIALIZER;
  }
  
  int Semaphore::P(){
      if(value &lt;= 0){
          pthread_cond_wait(&amp;c, &amp;m);
      }
      value--;
  }
  
  int Semaphore::V(){
      value++;
      if(value &gt; 0){
          pthread_cond_signal(&amp;c);
      }
  }
  </code></pre>