Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving an argument into a std::thread?

Please consider the following code:

void h(M m2) 
{ 
    ...
}

int main()
{
  while (true) {
    M m1 = ...;
    std::thread t(h, std::move(m1));
    t.detach();
  }
}

Is it guaranteed that m2 is properly move-d constructed from m1 before m1 is destroyed? Or is there a race?

like image 762
Andrew Tomazos Avatar asked Oct 17 '25 04:10

Andrew Tomazos


1 Answers

The standard seems clear to me:

Effects: Constructs an object of type thread. The new thread of execution executes INVOKE (DECAY_COPY ( std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...) with the calls to DECAY_COPY being evaluated in the constructing thread.

Since the copy is made in the calling thread it must complete before the constructor invocation returns.

Construction of m2 is done from a different object (the result of the DECAY_COPY), not from m1, so it doesn't matter whether m1 has been destroyed or not.

The result of the DECAY_COPY must be stored somewhere by the implementation so that it doesn't go out of scope until the target function has been initialized, but that is the implementation's job to get right. Destruction of m1 doesn't have any effect on it.

like image 93
Jonathan Wakely Avatar answered Oct 19 '25 20:10

Jonathan Wakely