condition_variable term不计算为采用0参数的函数

时间:2014-05-27 16:53:11

标签: c++ multithreading c++11 threadpool mutex

我在使用wait_variable和一个函数时遇到了问题。我希望我的主要等待,直到我的池线程完成所有这些任务,然后继续执行该程序。我想使用std::condition_variableisFinished()池函数来进行主等待。这就是我的所作所为:

//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.0\VC\include\condition_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>          ]

1 个答案:

答案 0 :(得分:4)

评估

pool.isFinished()并返回bool,但condition_variable::wait需要一个可重复调用的仿函数,以确定何时停止等待。您可以使用std::bind执行此操作:

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

或lambda:

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