我试图了解在条件变量的情况下虚假唤醒与丢失唤醒之间的区别。以下是我试过的小块代码。我知道在这种情况下“消费者”可能会在没有任何通知的情况下醒来,因此等待需要检查谓词。
但是wait with predicate 如何解决“丢失唤醒”的问题呢?正如你在下面的代码中看到的;'wait' 没有被调用 5 秒,我原以为它会错过前几个通知;但有了 predate,它不会错过任何一个。这些通知是否已保存以备将来等待?
#include <iostream>
#include <deque>
#include <condition_variable>
#include <thread>
std::deque<int> q;
std::mutex m;
std::condition_variable cv;
void dump_q()
{
for (auto x: q) {
std::cout << x << std::endl;
}
}
void producer()
{
for(int i = 0; i < 10; i++) {
std::unique_lock<std::mutex> locker(m);
q.push_back(i);
std::cout << "produced: " << i << std::endl;
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
locker.unlock();
}
}
void consumer()
{
while (true) {
int data = 0;
std::this_thread::sleep_for(std::chrono::seconds(5)); // <- should …Run Code Online (Sandbox Code Playgroud) c++ multithreading synchronization condition-variable race-condition