将lambdas传递给std :: thread和调用类方法 [英] Passing lambdas to std::thread and calling class methods

查看:254
本文介绍了将lambdas传递给std :: thread和调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个麻烦使用std :: thread和lambdas。我有一个方法TheMethod,我应该使用std :: thread并行化一些函数调用到同一个类中的方法。

I'm having a bit of trouble using std::thread together with lambdas. I have a method TheMethod where I should use std::thread to parallelize some function calls to methods in the same class.

我定义一个lambda函数,并尝试传递它如下面的std ::线程实例我创建:

I define a lambda function, and try to pass it as follows to the std::thread instance I create:

auto functor = 
   [this](const Cursor& c, size_t& result) ->void {result = classMethod(c);};

size_t a;
Cursor cursor = someCursor();

std::thread t1(functor, cursor, a);

t1.join();

不幸的是,编译器给了我:

Unfortunately, the compiler gives me:

  /usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<TheMethod...

我在lambda定义中尝试了很多组合,并且在调用std :: thread构造函数的方式,总是得到相同的错误。

I tried a lot of combinations in the lambda definition, and in the way of calling the std::thread constructor, but I get the same error always. The thread library is included, I link pthread too.

感谢提示!

推荐答案

您可以使用std :: ref通过引用传递参数:

You can use std::ref to pass the parameters by reference:

std::thread t1(functor, std::ref(cursor), std::ref(a))

参数在lambda本身的参数:

You could also capture the parameters by reference in the lambda itself:

size_t a;
Cursor cursor = someCursor();
std::thread t1([&] {a = classMethod(cursor);});
t1.join();

这篇关于将lambdas传递给std :: thread和调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆