gpt4 book ai didi

c++ - 是否有 `notify_one()` 的 `std::condition_variable` 队列?

转载 作者:行者123 更新时间:2023-11-30 01:03:11 27 4
gpt4 key购买 nike

考虑第一个线程函数和全局变量:

    std::mutex mut;
std::condition_variable officer;
bool firstPlayerIsReady = false;
bool secondPlayerIsReady = false;

void firstPlayer(){
constexpr auto doIt = true;
while(doIt)
{
std::unique_lock lock{mut};
auto toContinue = ring();
secondPlayerIsReady = true;
firstPlayerIsReady = false;
officer.notify_one(); //#1
if(!toContinue) return;
officer.wait(lock,[=](){ return firstPlayerIsReady;});
}
}

它调用一些 ring 并且 ring() 返回一个继续条件;然后在下一个循环中更新每个线程的就绪值;

考虑下一个话题:

void secondPlayer(){
constexpr auto doIt = true;
while(doIt)
{
auto period = std::chrono::seconds(5);
std::this_thread::sleep_for(period);

std::unique_lock lock{mut}; //#2
officer.wait(lock,[this](){ return secondPlayerIsReady;});
auto toContinue = ring();
firstPlayerIsReady = true;
secondPlayerIsReady = false;
officer.notify_one();
if(!toContinue) return;
}
}

此线程等待 5 秒后被 wait() 锁定,直到第一个线程调用 notify_one();更进一步,类似于第一个线程。

先验,带有#1 标签的行比带有#2 标签的行执行得早,因此通知在第二个线程被锁定之前发送。问题是——是否有一个 notify_one ( ) 队列?否则,显然不会发送通知。

最佳答案

没有队列。如果一个线程调用 notify_one 并且没有其他线程在等待它不会执行任何操作。

这就是为什么你有谓词,在你的例子中

officer.wait(lock,[this](){ return secondPlayerIsReady;});

所以当一个线程调用它时,如果 secondPlayerIsReady 为真,那么线程根本不会等待,而是跳过这一行。

因此,只要标志设置正确,过早地调用 notify_one 不是问题。请记住,标志在修改时需要由互斥体保护。

关于c++ - 是否有 `notify_one()` 的 `std::condition_variable` 队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54513521/

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