Condition_variable项的计算结果不是一个带有0个参数的函数

condition_variable term does not evaluate to a function taking 0 arguments

本文关键字:一个 参数 0个 函数 variable 计算 结果 Condition      更新时间:2023-10-16

我有一个问题使用等待与我的condition_variable和一个函数。我想让main 等待,直到池线程在继续执行程序之前完成它的所有任务。我想使用std::condition_variableisFinished()池函数使main等待。我是这样做的:

//above are tasks being queued in the thread pool
{
    std::unique_lock<std::mutex> lock(mainMut);
    waitMain.wait(lock, pool.isFinished());
}
//I need to make sure the threads are done with calculations before moving on

和我的pool.isFinished()

//definition in ThreadPool class
bool isFinished();
//implementation
bool ThreadPool::isFinished()
{
    {//aquire lock
        std::unique_lock<std::mutex>
            lock(queue_mutex);
        if(tasks.empty())
            return true;
        else
            return false;
    }//free lock
}

但是我得到了错误

C:Program Files (x86)Microsoft Visual Studio 11.0VCincludecondition_variable(66): error C2064: term does not evaluate to a function taking 0 arguments
1>          main.cpp(243) : see reference to function template instantiation 'void std::condition_variable::wait<bool>(std::unique_lock<_Mutex> &,_Predicate)' being compiled
1>          with
1>          [
1>              _Mutex=std::mutex,
1>              _Predicate=bool
1>          ]

pool.isFinished()被求值并返回bool,但condition_variable::wait需要一个函子,它可以反复调用该函子来确定何时停止等待。你可以使用std::bind:

waitMain.wait(lock, std::bind(&ThreadPool::isFinished, &pool));

或lambda:

waitMain.wait(lock, [&]{ return pool.isFinished(); });