#include <iostream>
#include <boost/thread.hpp>
using namespace std;
//关联多个线程的条件变量
boost::condition_variable cond;
//保护共享资源的互斥体
boost::mutex mutex;
//共享资源k
int k=0;
void func1(const int &id)
{
boost::unique_lock<boost::mutex> lock(mutex);
while(k<5)
{
cout<<"thread #"<<id<<" : k<5, waiting..."<<endl;
cond.wait(lock);
}
cout<<"thread #"<<id<<" : now k>5, printing..."<<endl;
}
void func2(const int &id)
{
boost::unique_lock<boost::mutex> lock(mutex);
cout<<"thread #"<<id<<" : k will be changed..."<<endl;
k+=5;
cond.notify_all();//唤醒所有的等待线程
cond.notify_one();//只会唤醒一个等待线程
}
int main()
{
boost::thread t1(func1, 11);
boost::thread t2(func1, 22);
boost::thread t3(func2, 33);
t1.join();
t2.join();
t3.join();
system("pause");
return 0;
}
C++ Boost 多线程(八),条件变量
最新推荐文章于 2020-07-31 13:33:20 发布