我正在尝试使用条件变量实现从两个线程按顺序打印数字,一个打印偶数,另一个打印奇数。
#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();
}
我在 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)
解锁锁并在返回之前再次锁定。这就是其他线程可以锁定并继续的方式。这就是必须将锁传递给等待函数的原因。
理想情况下,main 也应该在访问共享标志之前锁定。
关于c++ - 使用 boost 条件变量 boost scoped_lock 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39160329/