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



我有一个问题使用等待与我的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(); });

相关内容

  • 没有找到相关文章

最新更新