Boost scoped_lock usage with boost condition variables
<p>I am trying to use condition variables to implement printing of numbers in sequence from two threads, one printing even numbers and the other printing odd ones.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;boost/thread.hpp&gt;
#include &lt;condition_variable&gt;
using namespace std;

boost::mutex m;
boost::condition_variable cv_even;
boost::condition_variable cv_odd;
bool even_done = false;
bool odd_done = false;
bool wait_main = true;
void odd_printer(){
  cout&lt;&lt;"Start odd\n";
  int i = 0;
  while(true){
    boost::mutex::scoped_lock lock(m);
    cout&lt;&lt;"Odd acquired lock " &lt;&lt; i &lt;&lt; endl;
    while(!even_done) cv_odd.wait(lock);
    if(i % 2 == 1){
      cout&lt;&lt;i&lt;&lt;endl;
    }
    i++;
    even_done = false;
    odd_done = true;
    cv_even.notify_one();
  }
}

void even_printer(){
  cout&lt;&lt;"Start even\n";
  int i = 0;
  while(true){
    boost::mutex::scoped_lock lock(m);
    cout&lt;&lt;"Even acquired lock " &lt;&lt; i &lt;&lt; endl;
    while(!odd_done) cv_even.wait(lock);
    if(i % 2 == 0){
      cout&lt;&lt;i&lt;&lt;endl;
    }
    i++;
    odd_done = false;
    even_done = true;
    cv_odd.notify_one();
    cout&lt;&lt;"End scope even\n";
  }
}

int main(){
  boost::thread odd_t{odd_printer};
  boost::thread even_t{even_printer};
  sleep(2);
  odd_done = true;
  cv_even.notify_one();
  odd_t.join();
  even_t.join();
} 
</code></pre>

<p>The output I get before the <code>sleep(2)</code> statement finishes is:</p>

<pre><code>Start even
Even acquired lock 0
Start odd
Odd acquired lock 0
</code></pre>

<p>How can both the threads acquire the lock on mutex m. In other words the statement <code>boost::mutex::scoped_lock lock(m);</code> goes through in both the threads. Shouldn't one of them wait for the other one to release the lock on mutex m first?</p>