Boost scoped_lock使用Boost条件变量

Boost scoped_lock usage with boost condition variables

本文关键字:Boost 条件 变量 使用 lock scoped      更新时间:2023-10-16

我正在尝试使用条件变量来实现从两个线程中按顺序打印数字,一个打印偶数,另一个打印奇数。

#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 oddn";
  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 evenn";
  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 evenn";
  }
}
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();
} 

sleep(2)语句结束之前我得到的输出是:

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

两个线程如何获取互斥锁m上的锁?换句话说,语句boost::mutex::scoped_lock lock(m);在两个线程中都经过。它们中的一个不应该等待另一个先释放互斥对象m上的锁吗?

工作方式是cv.wait(lock)在返回之前解锁锁并再次锁定。这就是其他线程锁定并继续的方式。这就是为什么锁必须传递给wait-function的原因。

理想情况下,主程序应该在访问共享标志之前锁定。