gpt4 book ai didi

c++ - 条件变量和 notify_all

转载 作者:行者123 更新时间:2023-11-27 22:40:37 25 4
gpt4 key购买 nike

在下面的代码中(取自 cpp 引用并添加了额外的 cout)为什么我们看不到 ...finished waiting. 在第一个 cv.notify_all 之后?

#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::cerr << "I should see i here...\n";

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();
}

输出:

Waiting... 
Waiting...
Waiting...
Notifying...
I should see i here...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

最佳答案

因为这一行:

cv.wait(lk, []{return i == 1;});

您传递了一个谓词,因此只有当谓词返回 true 时它才会唤醒。在第一个 notify_all() 之后,谓词不满足。

关于c++ - 条件变量和 notify_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49326415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com