Violet Giraffe
Violet Giraffe

Reputation: 33579

Waiting for C++ 11 thread to actually start

How to wait until C++ 11 thread is started after it was created? It doesn't seem to have any method for that, unlike some other threading libraries (like Qt) that offer a special method to check if thread is running or not.

Upvotes: 7

Views: 6995

Answers (2)

Pete Becker
Pete Becker

Reputation: 76235

The language definition requires that the new thread has started before the constructor returns. Formally, that's [thread.thread.constr] /5: "The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f."

Upvotes: 12

user405725
user405725

Reputation:

I'm not sure why do you need to wait for it to start in a first place, but if you do, then you must use a mutex, a condition, and a flag indicated whether it is started or not. In a newly created thread, lock the mutex, set flag to «true» and notify waiter(s) on a conditional variable. In the code that creates a thread, lock the mutex, and check the flag. If the flag is «true» - your thread is started, if it is «false» then wait on a conditional variable and repeat once woken up.

Upvotes: 6

Related Questions