gpt4 book ai didi

c++ - std::condition_variable::notify_one() 调用两次

转载 作者:行者123 更新时间:2023-12-02 21:10:38 25 4
gpt4 key购买 nike

如果我在没有任何时间间隔的情况下调用 std::condition_variable::notify_one() 两次,将唤醒多少等待线程,如下所示:

{
std::unique_lock<std::mutex> lock(condvar_mutex);

condvar.notify_one();
condvar.notify_one();
}

是否可以保证这些通知将多次传递到不同的线程,而不是同一线程?

最佳答案

§30.5.1.7: If any threads are blocked waiting for *this, unblocks one of those threads.

不能保证它是不同的线程,只是它是一个线程。在两次 notify_one 调用之间的时间内,使用第一个 notify_one 唤醒的同一线程可能会被重新阻塞。

例如在以下示例中,不保证线程 3 是否会唤醒(忽略本示例中的虚假唤醒)。

- thread 1:

1 condvar.notify_one();
- 3 and 4 could run here.
2 condvar.notify_one();

- thread 2:

3 condvar.wait(/*...*/);
4 condvar.wait(/*...*/);

- thread 3:

5 condvar.wait(/*...*/);

关于c++ - std::condition_variable::notify_one() 调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084149/

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