30

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!

4
  • 15
    Say std::thread t1(functor, std::ref(cursor), std::ref(a)); Commented Mar 11, 2014 at 17:33
  • Indeed, now it compiles. Thanks @KerrekSB ! Commented Mar 11, 2014 at 17:35
  • you should mark the anwer as valid, so next time people will catch that this is the good answer Commented Mar 30, 2014 at 0:09
  • How can I do that? I only see the option to vote up next to Kerrek SBs answer. Sorry, I'm kind of new here. Commented Apr 2, 2014 at 9:03

2 Answers 2

54

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

I do want to warn that if t1 is detached and the main thread exits, calling a class method by reference without using std::ref is potentially dangerous.
1

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.

Hence, as answered by "alexk7", you should use std::ref or if you want to capture them pass by reference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.