#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex mu;
bool isSaleHalf = false;
bool isWork1Complete = false;
bool isWork2Complete = false;
void work_thread(bool& isComlete);
int main()
{
thread t1(work_thread, ref(isWork1Complete));
thread t2(work_thread, ref(isWork2Complete));
cout << "main thread : " << std::this_thread::get_id() << endl;
{
//通知前完成解锁,以避免等待线程才被唤醒就阻塞
lock_guard<mutex> lk(mu);
isSaleHalf = true;
}
cv.notify_all();
{
unique_lock<mutex> lk(mu);
cv.wait(lk, []() {return isWork1Complete && isWork2Complete; });
cout << "Complete" << endl;
}
t1.join();
t2.join();
return 0;
}
void work_thread(bool& isComlete)
{
{
unique_lock<mutex> lk(mu);
cv.wait(lk, []() {return isSaleHalf; });
}
{
//通知前完成解锁,以避免等待线程才被唤醒就阻塞
lock_guard<mutex> lk(mu);
cout << "thread " << this_thread::get_id() << " working" << endl;
//增加变量判断,避免虚假唤醒
isComlete = true;
}
cv.notify_one();
}
c++11 条件变量
最新推荐文章于 2024-05-13 19:06:29 发布