C++Mutex 和条件变量 Unlocking/Synchronisation

C++Mutex and conditional Variable Unlocking/Synchronisation

我想让几个线程都在等待一个条件变量 (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,与工人通知不同。