示例:
下面例子来自https://en.cppreference.com/w/cpp/thread/condition_variable/wait.
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
std::condition_variable cv;
std::mutex cv_m; // This mutex is used for three purposes:
// 1) to synchronize accesses to i
// 2) to synchronize accesses to std::cerr
// 3) for the condition variable cv
int i = 0;
void waits()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cerr << "Waiting... \n";
cv.wait(lk, []{return i == 1;});
std::cerr << "...finished waiting. i == 1\n";
}
void signals()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(cv_m);
std::cerr << "Notifying...\n";
}
cv.notify_all();
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(cv_m);
i = 1;
std::cerr << "Notifying again...\n";
}
cv.notify_all();
}
int main()
{
std::thread t1(waits), t2(waits), t3(waits), t4(signals);
t1.join();
t2.join();
t3.join();
t4.join();
}
Possible output:
Waiting...
Waiting...
Waiting...
Notifying...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1
关键点
锁的作用
在上面的例子中锁有三点作用,注释代码已经说的很清楚,另外notify时是否需要加锁,详见cppreference。
通知丢失
先notify_all后调用不带谓词的wait时,当前线程会进入等待,之前的notify_all会丢失。解决此问题的办法是使用带谓词版本的wait函数。
虚假唤醒
网上关于虚假唤醒的原因有各种各样的说法,不管是哪一种说法,最后的现象是等待的线程被唤醒了,但是线程运行的条件不满足。解决此问题的办法是使用带谓词版本的wait函数。