Is joinable() then join() thread-safe in std::thread?

Viewed 1877

In a std::thread, an exception is throw if I call join() and the thread is not joinable.

So I do :

if (thread.joinable())
  thread.join();

Now imagine that the thread is terminated after the joinable() and before the join() (due to thread scheduling).

Is this case possible in the worth situation ? Do I really need to use a try / catch around join() ?

1 Answers

Now imagine that the thread is terminated after the joinable() and before the join() (due to thread scheduling).

If thread just terminated it does not become not joinable, std::thread::join() will just successfully return immediately in such case as it said in documentation for std::thread::joinable():

A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

It can become not joinable if you call std::sthread::join() for the same thread concurrently.

Is this case possible in the worth situation ? Do I really need to use a try / catch around join() ?

Only if you try to call std::thread::join() for the same thread from multiple threads. You better avoid that and have only one thread manage others.

Related