gpt4 book ai didi

c++ - c++线程中的notify_one()唤醒多个线程

转载 作者:搜寻专家 更新时间:2023-10-30 23:52:57 24 4
gpt4 key购买 nike

您好,我有以下代码:

// condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) cv.wait(lock);
// ...
std::cout << "thread " << id << std::endl;
}

void go() {
std::unique_lock<std::mutex> lock(mtx);
ready = true;
cv.notify_one();
}

int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);

std::cout << "10 threads ready to race..." << std::endl;
go(); // go!

for (auto& th : threads) th.join();
std::cout << "Finished!" << std::endl;

return 0;
}

这是输出:

10 threads ready to race...
thread 9
thread 0

我的期望是,通过调用 notify_one(),只会通知一个线程,我会陷入死锁。但在这种情况下,两个线程在重新发生死锁之前得到通知。我在这里错过了什么?谢谢

最佳答案

当您调用 go() 时,可能并非所有线程都已启动。那么这可能会发生:

  1. 9 个线程正在运行并等待条件变量。
  2. 您调用 go()ready 设置为 true 并通知线程零。
  3. 第十个线程启动,它看到 readytrue 并且不等待条件变量。

关于c++ - c++线程中的notify_one()唤醒多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42714632/

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