title: Two std::unique_lock used on same mutex causes deadlock ?
body: <p>I found this <a href="https://codereview.stackexchange.com/questions/84109/a-multi-threaded-producer-consumer-with-c11">code</a> on code review stack exchange which implements a producer-consumer problem. I am posting a section of code here.</p>
  
  <p>In the given code, let's consider a scenario when producer produces a value by calling <code>void add(int num)</code>, it acquires lock on mutex <code>mu</code> and  <code>buffer.size()==size_</code> this makes the producer go on wait queue due to the conditional variable <code>cond</code>.</p>
  
  <p>At the same moment, a context switch takes place and consumer calls function <code>int remove()</code> to consume value , it tries to acquire the lock on mutex <code>mu</code> , however the lock has already been acquired previously by the producer so it fails and never consumes the value, hence causing a deadlock.</p>
  
  <p>Where am I going wrong here ? Because the code seems to work properly when I run it, debugging it didn't help me.</p>
  
  <p>Thanks</p>
  
  <pre><code>void add(int num) {
          while (true) {
              std::unique_lock&lt;std::mutex&gt; locker(mu);
              cond.wait(locker, [this](){return buffer_.size() &lt; size_;});
              buffer_.push_back(num);
              locker.unlock();
              cond.notify_all();
              return;
          }
      }
      int remove() {
          while (true)
          {
              std::unique_lock&lt;std::mutex&gt; locker(mu);
              cond.wait(locker, [this](){return buffer_.size() &gt; 0;});
              int back = buffer_.back();
              buffer_.pop_back(); 
              locker.unlock();
              cond.notify_all();
              return back;
          }
      }
  </code></pre>