Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of std::thread arguments

When parameters are passed to std::thread(), does the thread from which the new thread is being spawned wait until all the parameters are completely copied into new thread local storage?

Simple example:

void f()
{  
  int array[10];
  ........ //done something with array  
  std::thread th(someF, array); //assuming that someF accepts int[]  
  th.detach();  
}

Should I automatically assume that all the data is safely copied before f() has ended? One of the scenarios I see, assuming f() doesn't wait, and plows full steam ahead, is that th is attempting to copy array that is being in destroyed.

like image 602
newprint Avatar asked Nov 15 '13 07:11

newprint


2 Answers

Yes. If it fails to copy it will throw in the constructing thread.

§30.3.1.2 thread constructors

template explicit thread(F&& f, Args&&... args);

Requires: F and each Ti in Args shall satisfy the MoveConstructible requirements. INVOKE (DECAY_- COPY ( std::forward(f)), DECAY_COPY (std::forward(args))...) (20.8.2) shall be a valid expression. 4

Effects: Constructs an object of type thread. The new thread of execution executes INVOKE (DECAY_- COPY ( std::forward(f)), DECAY_COPY (std::forward(args))...) with the calls to DECAY_COPY being evaluated in the constructing thread. Any return value from this invocation is ignored. [ Note: This implies that any exceptions not thrown from the invocation of the copy of f will be thrown in the constructing thread, not the new thread. —end note ] If the invocation of INVOKE (DECAY_COPY ( std::forward(f)), DECAY_COPY (std::forward(args))...) terminates with an uncaught exception, std::terminate shall be called.

Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

like image 133
ronag Avatar answered Nov 13 '22 15:11

ronag


Yes, if the arguments cannot be copied, to storage available to the new thread, it will throw an exception.

From http://en.cppreference.com/w/cpp/thread/thread/thread

Any exceptions thrown during evaluation and copying/moving of the arguments are thrown in the current thread, not the new thread.

like image 45
Phillip Kinkade Avatar answered Nov 13 '22 17:11

Phillip Kinkade