简体   繁体   中英

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

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.

It is not thread safe. If you have more than one thread that can call your snippet at any time, you may experience a race condition. The only real way to protect against this is by wrapping your snippet in an std::mutex shared by the threads calling said snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM