我在将 wait 与我的 condition_variable 和函数一起使用时遇到问题。我希望我的 main 等待,直到我的池线程完成所有任务,然后再继续执行该程序。我想使用 std::condition_variable
和 isFinished()
池函数来让 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.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> ]
最佳答案
pool.isFinished()
被评估并返回一个 bool
,但是 condition_variable::wait
需要一个可以重复调用的仿函数确定何时停止等待。您可以使用 std::bind
执行此操作:
waitMain.wait(lock, std::bind(&ThreadPool::isFinished, &pool));
或 lambda:
waitMain.wait(lock, [&]{ return pool.isFinished(); });
关于c++ - condition_variable 项不计算为采用 0 个参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23894876/