Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() ?

like image 681
Vincent LE GARREC Avatar asked Feb 21 '20 13:02

Vincent LE GARREC


People also ask

What do you mean by join () and joinable () in multithreading?

If the program needs to know when that thread of execution has completed, some other mechanism needs to be used. join() cannot be called on that thread object any more, since it is no longer associated with a thread of execution. It is considered an error to destroy a C++ thread object while it is still "joinable".

When a thread is joinable?

A thread object is said to be joinable if it identifies/represent an active thread of execution. A thread is not joinable if: It was default-constructed. If either of its member join or detach has been called.

Is thread joinable by default?

thread::joinable So a default constructed thread is not 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.

What does std :: thread join do?

std::thread::join. Blocks the current thread until the thread identified by *this finishes its execution. The completion of the thread identified by *this synchronizes with the corresponding successful return from 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.

like image 69
Slava Avatar answered Oct 12 '22 06:10

Slava