[英]Passing lambdas to std::thread and calling class methods
我在使用std :: thread和lambdas时遇到了一些麻烦。 我有一个方法TheMethod我应该使用std :: thread来并行化对同一个类中的方法的一些函数调用。
我定义了一个lambda函数,并尝试将它传递给我创建的std :: thread实例:
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();
不幸的是,编译器给了我:
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<TheMethod...
我在lambda定义中尝试了很多组合,并且调用了std :: thread构造函数,但是我总是得到相同的错误。 包含了线程库,我也链接了pthread。
谢谢你的提示!
您可以使用std :: ref通过引用传递参数:
std::thread t1(functor, std::ref(cursor), std::ref(a))
您还可以通过lambda本身中的引用捕获参数:
size_t a;
Cursor cursor = someCursor();
std::thread t1([&] {a = classMethod(cursor);});
t1.join();
这是因为对象游标和a通过值传递给线程的构造函数。 仿函数引用了新创建的线程的本地副本,而不是您期望它们的对象。
因此,正如“alexk7”所回答的那样,你应该使用std :: ref,或者如果你想通过引用捕获它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.