函数中的四个线程

Four Threads in Function

本文关键字:四个 线程 函数      更新时间:2023-10-16

我有4个线程应该进入相同的函数A.

  1. 我想允许只有两个人可以表演
  2. 我想等待所有四个,然后执行函数A

我应该怎么做(在C++中)?

C++中的条件变量在这里就足够了。

这应该适用于只允许两个线程同时进行:

// globals
std::condition_variable cv;
std::mutex m;
int active_runners = 0;
int FunctionA()
{
   // do work
}
void ThreadFunction()
{
    // enter lock and wait until we can grab one of the two runner slots
    {
        std::unique_lock<std::mutex> lock(m); // enter lock
        while (active_runners >= 2)  // evaluate the condition under a lock
        {
            cv.wait();  // release the lock and wait for a signal
        }
        active_runners++; // become one of the runners
    } // release lock
    FunctionA();
    // on return from FunctionA, notify everyone that there's one less runner
    {
        std::unique_lock<std::mutex> lock(m); // enter lock
        active_runners--;
        cv.notify(); // wake up anyone blocked on "wait"
    } // release lock
}