【问题标题】:Issue in predicate function in wait in thread C++线程 C++ 中等待中的谓词函数问题
【发布时间】:2016-05-02 22:37:42
【问题描述】:

我试图将条件放在一个函数中,但它会引发令人困惑的编译时错误。如果我用这样的 lambda 函数编写它 []{ retur i == k;} 它显示 k is unidentified 。谁能告诉如何解决这个问题。

#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex m;
int i;
bool check_func(int i,int k)
{
    return i == k;
}
void print(int k)
{
   unique_lock<mutex> lk(m);
   cv.wait(lk,check_func(i,k));            // Line 33
   cout<<"Thread no. "<<this_thread::get_id()<<" parameter "<<k<<"\n";
   i++;
   return;
}
int main() 
{
    thread threads[10];
    for(int i = 0; i < 10; i++)
       threads[i] = thread(print,i);
    for(auto &t : threads)
       t.join();
    return 0;
}

编译器错误:

In file included from 6:0:
/usr/include/c++/4.9/condition_variable: In instantiation of 'void std::condition_variable::wait(std::unique_lock<std::mutex>&, _Predicate) [with _Predicate = bool]':
33:30:   required from here
/usr/include/c++/4.9/condition_variable:97:14: error: '__p' cannot be used as a function
  while (!__p())
              ^

【问题讨论】:

    标签: multithreading c++11 mutex wait condition-variable


    【解决方案1】:

    wait() 接受一个谓词,它是一个返回 bool 的 可调用 一元函数。 wait() 使用这样的谓词:

    while (!pred()) {
        wait(lock);
    }
    

    check_func(i,k)bool。它是不可调用的,它是一个 constant - 这违背了目的。你在等待可以改变的东西。你需要将它包装在可以重复调用的东西中——比如 lambda:

       cv.wait(lk, [&]{ return check_func(i,k); });
    

    【讨论】:

    • 澄清一下,它并不是一个真正的常量——它是一个计算结果为布尔值的表达式,该值是传递给wait(而不是函数本身)的值。跨度>
    • 我相信在 check_func 之前应该有一个 return 关键字。之后它不会导致任何编译时错误。但是在那之后它被挂起并导致时间限制超过并且没有打印任何东西出来?
    • @user 好吧,你所有的线程都在等待一些永远不会发生的事情发生。这是一个编程逻辑错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2021-11-14
    • 2013-02-03
    • 1970-01-01
    相关资源
    最近更新 更多