Passing lambdas to std::thread and calling class methods Passing lambdas to std::thread and calling class methods multithreading multithreading

Passing lambdas to std::thread and calling class methods


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();


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.