C++ 将 lambdas 传递给 std::thread 并调用类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22332181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing lambdas to std::thread and calling class methods
提问by user46317
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.
我在将 std::thread 与 lambdas 一起使用时遇到了一些麻烦。我有一个方法 TheMethod ,我应该使用 std::thread 将一些函数调用并行化到同一类中的方法。
I define a lambda function, and try to pass it as follows to the std::thread instance I create:
我定义了一个 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();
Unfortunately, the compiler gives me:
不幸的是,编译器给了我:
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type' in ‘class std::result_of<TheMethod...
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.
我在 lambda 定义和调用 std::thread 构造函数的方式中尝试了很多组合,但我总是得到相同的错误。包含线程库,我也链接了 pthread。
Thanks for hints!
感谢您的提示!
回答by alexk7
You can use std::ref to pass the parameters by reference:
您可以使用 std::ref 通过引用传递参数:
std::thread t1(functor, std::ref(cursor), std::ref(a))
You could also capture the parameters by reference in the lambda itself:
您还可以通过 lambda 本身的引用捕获参数:
size_t a;
Cursor cursor = someCursor();
std::thread t1([&] {a = classMethod(cursor);});
t1.join();
回答by sarup dalwani
This is because the objects cursor and a are passed by value to the constructor of thread. The functor takes a reference to the local copies of the newly created thread and not on the objects you expected them to be .
这是因为对象 cursor 和 a 是按值传递给线程的构造函数的。函子引用新创建线程的本地副本,而不是您期望它们的对象。
Hence, as answered by "alexk7", you should use std::ref or if you want to capture them pass by reference
因此,正如“alexk7”所回答的,您应该使用 std::ref 或者如果您想通过引用捕获它们