title: Implementing semaphore by using mutex operations and primitives
body: <p>Some time ago had an interview and was asked to implement
  Semaphore by using mutex operations and primitives only
  (he allowed int to be considered as atomic). I came with solution below.
  He did not like busy/wait part -- <code>while (count &gt;= size) {}</code> -- and asked to implement locking instead by using more primitive
  types and mutexes. I did not manage to come with improved solution.
  Any ideas how it could be done?</p>
  
  <pre><code>struct Semaphore {
  int size;
  atomic&lt;int&gt; count;
  mutex updateMutex;
  
  Semaphore(int n) : size(n) { count.store(0); }
  
  void aquire() {
      while (1) {
          while (count &gt;= size) {}
          updateMutex.lock();
          if (count &gt;= size) {
              updateMutex.unlock();
              continue;
          }
          ++count;
          updateMutex.unlock();
          break;
      }
  }
  
  void release() {
      updateMutex.lock();
      if (count &gt; 0) {
          --count;
      } // else log err
      updateMutex.unlock();
  }
  };
  </code></pre>