c++ - condition_variable 项不计算为采用 0 个参数的函数

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

我在将 wait 与我的 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.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/

相关文章:

c++ - Cent OS 6.3 上 usleep 的 CPU 使用率高

c++ - 在 C++14 中使用 hana::transform 转换元组内部的类型

javascript - NodeJS - 是否可以有两个独立的集群?

c++ - 数组指针,(*ptr)[] 和 *ptr[] 有什么区别

c++ - 带有 C++11 线程的 Qtcreator

c++ - type(myVar) 和 (type)myVar 的名称是什么?他们都是不好的做法吗?

c++ - 删除类列表的静态成员的元素

c++ - 为什么非平凡成员需要在同一类中为匿名 union 定义构造函数

c++ - 线程中指向this*的指针

python - Python 线程上的守护进程属性的含义