gpt4 book ai didi

c++ - condition_variable.notify同步点吗?

转载 作者:行者123 更新时间:2023-12-01 14:44:11 25 4
gpt4 key购买 nike

假设我有这样的事情:

bool signalled = false;
std::condition_variable cv;
void thread1() {
while (true) {
std::unique_lock l(mutex);
cv.wait_until(l, [] { return signalled; });
return;
}
}

void thread2...N() {
signalled = true;
cv.notify_all();
}

那被认为是线程安全的吗?在许多线程中,可以将 bool 值设置为true来中断thread1。

编辑:如果不是线程安全的,我正在寻找有关竞赛条件的描述,以便我可以更好地理解根本问题并填补知识空白。

最佳答案

无需同步即可写入非原子变量。但是,将signalled设置为atomic<bool>将无法解决问题。
std::condition_variable上的C++ reference读取:

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.



你应该做这个:
bool signalled = false;

void thread2...N()
{
std::unique_lock l(mutex);
signalled = true;
cv.notify_all();
}

相关问题:
  • Mutex protecting std::condition_variable
  • Shared atomic variable is not properly published if it is not modified under mutex
  • Why do I need to acquire a lock to modify a shared "atomic" variable before notifying condition_variable
  • 关于c++ - condition_variable.notify同步点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845679/

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