首页 > 解决方案 > 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,最终需要全部使用。稍后我将编写一个函数来管理它。

标签: c++multithreadingconditional-statementsmutex

解决方案


cv.wait(lck, [] {return finished[0] == true; });在主线程中,但没有收到通知。

您需要通知它,并且您最好使用另一个来通知它,与condition_variable工作人员的广告通知不同。


推荐阅读