简体   繁体   English

在 std::thread 中 joinable() 然后 join() 是线程安全的吗?

[英]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.std::thread中,如果我调用join()并且线程不可连接,则会引发异常。

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).现在假设线程在joinable()之后和join()之前终止(由于线程调度)。

Is this case possible in the worth situation?这种情况在价值情况下可能吗? Do I really need to use a try / catch around join() ?我真的需要在join()周围使用try / catch吗?

Now imagine that the thread is terminated after the joinable() and before the join() (due to thread scheduling).现在想象线程在 joinable() 之后和 join() 之前终止(由于线程调度)。

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() :如果线程刚刚终止,它不会变得不可连接, std::thread::join()将在这种情况下立即成功返回,如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.如果您同时为同一个线程调用std::sthread::join() ,它可能变得不可连接。

Is this case possible in the worth situation ?这种情况在值得的情况下可能吗? Do I really need to use a try / catch around join() ?我真的需要在 join() 周围使用 try / catch 吗?

Only if you try to call std::thread::join() for the same thread from multiple threads.仅当您尝试从多个线程为同一线程调用std::thread::join() 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.防止这种情况的唯一真正方法是将您的代码段包装在调用所述代码段的线程共享的std::mutex中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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