Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing lambdas to std::thread and calling class methods

Tags:

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!

like image 202
user46317 Avatar asked Mar 11 '14 17:03

user46317


1 Answers

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(); 
like image 152
alexk7 Avatar answered Sep 19 '22 12:09

alexk7