C 线程中的notify_one()醒来多个线程
notify_one() in c++ thread waking up more than one thread
你好,我有以下代码:
// 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()
时启动所有线程。然后这可能会发生:
- 九个线程正在运行并等待条件变量。
- 您调用将
ready
设置为true
并通知线程零的go()
。 - 启动了第十个线程,看到
ready
是true
,不等待条件变量。
您不应指望通知线程的数量。notify_one
醒来"至少一个,如果存在等待线程"。
C 标准允许虚假唤醒,这意味着无通知醒来的线程。
相反,请检查您在静音中保护的变量。如果需要确切的通知行为,则可以考虑添加计数器。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- C 线程中的notify_one()醒来多个线程
- 线程没有从睡眠中醒来
- 提振.线程在1.58中醒来太晚了