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.
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...
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.
Thanks for hints!
You can use std::ref to pass the parameters by reference:
std::thread t1(functor, std::ref(cursor), std::ref(a))
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With