title: Semaphore implementation using x86 assembly
body: <p>I am interested in the semaphore implemenation scheme, and I learned that in the x86, we could use the "lock prefix" to implement atomic operations, and I want to use it to implement a mutex, I know that C++ 11 has standard mutex now, but I want to implement my own. and here is my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;vector&gt;
  
  struct Semaphore
  {
  private:
      int s;
  public:
      Semaphore( int s ) : s(s){}
      void wait()
      {
          int *p = &amp;s;
          _asm
          {
              mov eax, p
              lock dec DWORD PTR [eax]
      begin : mov ebx, DWORD PTR [eax]
              cmp ebx, 0
              jl begin
          };
      }
  
      void signal()
      {
          int *p = &amp;s;
          _asm
          {
              mov eax, p
              lock inc DWORD PTR [eax]
          };
      }
  } s(1);
  
  void print()
  {
      s.wait();
      std::cout &lt;&lt; "Print Thread " &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;
      s.signal();
  }
  
  int main( int argc, char* argv )
  {
      std::vector&lt; std::thread &gt; vec;
      int n = 3;
      for( int i = 0; i &lt; n; ++i ) vec.push_back( std::thread( print ) );
      for( int i = 0; i &lt; n; ++i ) vec[i].join();
  
      return 0;
  }
  </code></pre>
  
  <p>The problem is that when there is two thread, the code goes well, while in case of 3 threads, the program seems to sink into a deadlock condition, could anyone explain why or give me some suggestions on how to implement is on a x86 machine?</p>