【发布时间】:2021-09-29 16:53:29
【问题描述】:
我想让几个线程都在等待一个条件变量 (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,最终需要全部使用。稍后我将编写一个函数来管理它。
【问题讨论】:
-
你能使用 C++20 的特性吗?
标签: c++ multithreading conditional-statements mutex