我有4个线程应该输入相同的功能A.
我该怎么做(用C ++编写)?
答案 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
}