【发布时间】:2016-08-26 07:08:55
【问题描述】:
我正在尝试使用条件变量来实现从两个线程按顺序打印数字,一个打印偶数,另一个打印奇数。
#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); 语句在两个线程中都经过。他们中的一个不应该等待另一个先释放 mutex m 上的锁吗?
【问题讨论】:
标签: c++ multithreading boost