title: Implementing Binary Semaphore using atomic<int>
body: <p>I have written this code to demonstrate Binary Semaphore using only atomic .</p>
  <p>1 thread producer will push 100 elements in the queue initially.</p>
  <p>later threads 2 and 3 which is the consumer will run in parallel to consume this queue.</p>
  <p>The issue is: I can see the same data/element print by both the threads</p>
  <p>BinarySemaphore.cpp</p>
  <pre><code>std::queue&lt;int&gt; buffer;
  int s_data = 1;
  
  
  struct Semaphore
  {
      Semaphore():s_(1)
      {
  
      }
      void wait()
      {
          while( s_.load() ==  0);    //you will keep waiting here until s_ becomes 1
          s_.fetch_sub(1);
      }
  
      void signal()
      {
          s_.fetch_add(1);
      }
  
      private :
      std::atomic&lt;int&gt; s_ ;
  
  };
  
  Semaphore s; 
  
  
  void producer()
  {
      
      while(s_data &lt;= 100)
      {
          s.wait();
  
          // critical section starts
          {
              
              std::ostringstream oss;
              oss &lt;&lt; &quot;Consumer pushing data &quot; &lt;&lt; s_data &lt;&lt;endl;
  
              cout &lt;&lt; oss.str();
              
              buffer.push(s_data++);
          }
          // critical section ends
  
          s.signal();
      }
  }
  
  void consumer()
  {
      while (1)
      {
          s.wait();
          // critical section starts
          if (!buffer.empty())
          {
              int top = buffer.front();
              buffer.pop();
  
              std::ostringstream oss;
              oss &lt;&lt; &quot;consumer  thread id= &quot; &lt;&lt; this_thread::get_id() &lt;&lt;  &quot; reading data = &quot; &lt;&lt; top  &lt;&lt; endl;
              cout &lt;&lt; oss.str();
          }
          // critical section ends
          s.signal();
      }
  }
  
  
  
  
  int main()
  {
      Semaphore s;
  
      std::thread prod(producer);
  
      prod.join();
  
      std::thread cons1(consumer);
      std::thread cons2(consumer);
  
  
      cons1.join();
      cons2.join();
  
  }
  </code></pre>