简体   繁体   中英

Boost scoped_lock usage with boost condition variables

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.

#include <iostream>
#include <boost/thread.hpp>
#include <condition_variable>
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<<"Start odd\n";
  int i = 0;
  while(true){
    boost::mutex::scoped_lock lock(m);
    cout<<"Odd acquired lock " << i << endl;
    while(!even_done) cv_odd.wait(lock);
    if(i % 2 == 1){
      cout<<i<<endl;
    }
    i++;
    even_done = false;
    odd_done = true;
    cv_even.notify_one();
  }
}

void even_printer(){
  cout<<"Start even\n";
  int i = 0;
  while(true){
    boost::mutex::scoped_lock lock(m);
    cout<<"Even acquired lock " << i << endl;
    while(!odd_done) cv_even.wait(lock);
    if(i % 2 == 0){
      cout<<i<<endl;
    }
    i++;
    odd_done = false;
    even_done = true;
    cv_odd.notify_one();
    cout<<"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();
} 

The output I get before the sleep(2) statement finishes is:

Start even
Even acquired lock 0
Start odd
Odd acquired lock 0

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

The way this works is that cv.wait(lock) unlocks the lock and locks again before returning. That's how the other threads can lock and continue. That is the reason why the lock must be passed to the wait-function.

Ideally, the main should also lock before accessing the shared flags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM