liveBook · Manning

Thread argument passing

As explained in C++ Concurrency in Action, Second Edition

Thread argument passing is the behavior governing how arguments are stored and supplied when starting a thread function.

std::thread stores its supplied arguments and invokes the thread function with those stored values as rvalues. Use std::ref when the function needs a non-const reference to the original object. section 2.2

Choose how each argument reaches the new thread:

  • Wrap an lvalue in std::ref to pass it by reference; ensure it remains alive until the thread has finished. section 2.2
  • Pass an owning std::string rather than a pointer to a local buffer when detaching a thread. section 2.2
  • Use std::move to transfer a move-only argument such as std::unique_ptr; member-function calls take the object pointer first. section 2.2
std::thread t(update_data_for_widget,w,std::ref(data));


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":39},{\"line\":0,\"ch\":53}]]"}
!@%STYLE%@!

See the std::ref change that passes the original data object to the thread function. section 2.2

void process_big_object(std::unique_ptr<big_object>);
std::unique_ptr<big_object> p(new big_object);
p->prepare_data(42);
std::thread t(process_big_object,std::move(p));

See a unique_ptr moved into a thread function. section 2.2

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains stored-argument invocation through references, lifetimes, member functions, and move-only values.
Examples
Uses detached threads, a non-const reference, a member-function pointer, and a moved unique_ptr.
What you can do after
Apply std::thread argument handling by wrapping references with std::ref and moving move-only values.
How it connects
Connects argument passing to std::bind, std::ref, member-function pointers, and move semantics.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.