C++11 条件变量::等待意外行为?

C++11 条件变量::等待意外行为?,c++11,C++11,我从电话里找到了密码。参考文件指出: 等待导致当前线程阻塞,直到条件变量 被通知或发生虚假唤醒,可选择循环直到 谓词满足 该链接还声明等待相当于: 而(!pred()){ 等等(锁);} 如果是这样的话,是否有原因说明以下代码不能作为原始代码工作 #include <condition_variable> #include <iostream> #include <mutex> #include <thread> std::condition_v

我从电话里找到了密码。参考文件指出:

等待导致当前线程阻塞,直到条件变量 被通知或发生虚假唤醒,可选择循环直到 谓词满足

该链接还声明等待相当于:

而(!pred()){ 等等(锁);}

如果是这样的话,是否有原因说明以下代码不能作为原始代码工作

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

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, [] {std::cout << "Check Done!" << std::endl; 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();
}
#包括
#包括
#包括
#包括
std::条件变量cv;
std::mutex cv_m;//此互斥用于三个目的:
//1)同步对i的访问
//2)同步对std::cerr的访问
//3)对于条件变量cv
int i=0;
void waits()
{
std::唯一锁定lk(cv_m);

你希望什么?在你设置了
i=1
之后,你永远不会
通知所有人,所以任何
等待
线程完成等待的唯一方式就是如果他们有一个虚假的唤醒,并且碰巧注意到
i==1
。我正在阅读这个博客中的“Lost Wakup”部分。那里的描述让我感到困惑要相信当谓词为true时,等待会自动退出。好吧,这是一个误解。您需要
通知
,否则等待线程可能永远无法唤醒以检查条件是否为true。因此,除了设置谓词并希望虚假唤醒bl之外,没有办法处理为丢失唤醒场景ess us?丢失的唤醒(应该是丢失的通知i.m.o)已在您的代码中处理。
wait
在进入等待模式之前检查状态。我看到文章也提到:如何解决此问题?清除虚假唤醒的谓词也有助于丢失唤醒。如果谓词为
true
,则接收方可以独立于发送方的通知继续其工作