功能中的四个线程

时间:2015-11-20 18:19:36

标签: c++ multithreading algorithm

我有4个线程应该输入相同的功能A.

  1. 我想允许只有两个人可以表演。
  2. 我想等待所有四个,然后执行功能A.
  3. 我该怎么做(用C ++编写)?

1 个答案:

答案 0 :(得分:0)

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
}