c++ - C++Mutex 和条件变量解锁/同步
问题描述
我想让几个线程都在等待一个条件变量(CV),当主线程更新一个变量时,它们都会执行。但是,我需要主线程等到所有这些都完成后再继续。其他线程没有结束,只是返回并再次等待,所以我不能使用 thread.join() 例如。
我已经完成了前半部分的工作,我可以触发线程,但是主线程只是挂起并且不会继续。以下是我当前的代码
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <Windows.h>
#define N 3
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
bool finished[N];
void print_id(int id) {
while (1) {
std::unique_lock<std::mutex> lck(mtx); //Try and Lock the Mutex
while (finished[id]) cv.wait(lck); //Wait until finished is false
// ...
std::cout << "thread " << id << '\n';
finished[id] = true; //Set finished to be true. When true, program should continue
}
}
int main()
{
std::thread threads[N];
// spawn 10 threads:
for (int i = 0; i < N; ++i) {
threads[i] = std::thread(print_id, i); //Create n threads
finished[i] = true; //Set default finished to be true
}
std::cout << "N threads ready to race...\n";
for (int i = 0; i < 5; i++) {
std::unique_lock<std::mutex> lck(mtx); //Lock mutex
for (int i = 0; i < N; i++) {
finished[i] = false; //Set finished to false, this will break the CV in each thread
}
cv.notify_all(); //Notify all threads
cv.wait(lck, [] {return finished[0] == true; }); //Wait until all threads have finished (but not ended)
std::cout << "finished, Sleeping for 2s\n";
Sleep(2000);
}
return 0;
}
谢谢你。
编辑:我知道我目前只检查已完成 [0] 的状态,而不是每个状态。这样做只是为了简单 atm,最终需要全部使用。稍后我将编写一个函数来管理它。
解决方案
您cv.wait(lck, [] {return finished[0] == true; });
在主线程中,但没有收到通知。
您需要通知它,并且您最好使用另一个来通知它,与condition_variable
工作人员的广告通知不同。
推荐阅读
- fuse - 如何在 S3FS 中制造“传输端点未连接”问题(用于测试解决方法)
- java - 如何在我的项目中使用 SCA mvn 插件在 Fortify SCA 扫描中仅包含一个文件夹?
- flutter - Flutter:致命错误:找不到“Flutter/Flutter.h”文件
- c# - 如何在 App.config 中配置 serilog 和 applicationinsights?
- python - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 107654: invalid start byte Django 数据库更改为 MySQL
- sql - 选择最近的记录(带有到期日期)
- yaml - 使用 yq 在不知道键名的情况下获取键和特定值
- php - 字段“标识符”没有默认值 - Laravel
- python - 如何训练一个只有少数类被错误分类的模型,然后将它们与所有其他类(包括那几个类)合并?
- flutter - 如何在 Flutter 中重新排序 GridView?