#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 多线程(八),条件变量
猜你喜欢
转载自blog.csdn.net/u012592062/article/details/80470405
今日推荐
周排行