Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a thread whose main function requires a reference argument?

I need to create a reference to a variable in a thread. When I do it like in the code below, I get two errors:

C2672: 'std::invoke': no matching overloaded function found

C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'

How to code it correctly?

#include <thread>

void foo(double a, double& b)
{
  b = a;
}

int main()
{
  double a = 0.0, b = 0.0;

  std::thread f(foo, a, b);

  f.join();
}
like image 549
Perotto Avatar asked Apr 05 '26 23:04

Perotto


1 Answers

That is what std::reference_wrapper and its two creator functions, std::ref and std::cref are for:

std::thread f(foo, a, std::ref(b));

[Live example]

std::reference_wrapper<T> is an object which effectively behaves like a rebindable reference: it defines operator T& for implicit conversin into T&, but can be reassigned. It is intended precisely for situations where a "copyable reference" is needed, such as std::bind or std::thread.

Use std::ref to create a non-const reference to x, and std::cref to create a const reference to x.

like image 119
Angew is no longer proud of SO Avatar answered Apr 08 '26 13:04

Angew is no longer proud of SO