C ++ 11安全地加入线程,而不使用try / catch块 [英] C++11 safely join a thread without using a try / catch block
问题描述
根据文档此处和 here ,C ++ 11线程的join方法会抛出一个 std :: system_error
if joinable()== false
。因此,等待一个线程完成执行的自然方法是这样的:
According to the documentation here and here, the join method of a C++11 thread will throw a std::system_error
if joinable() == false
. Thus the natural way to wait for a thread to complete execution is something along the lines of:
if (thread2.joinable()) thread2.join();
然而,这有可能抛出一个std :: system_error。考虑线程1调用thread2.joinable(),返回true,表示thread2仍在运行。然后调度程序暂停thread1并将上下文切换到线程2.线程2完成,然后线程1恢复。线程1调用thread2.join(),但是线程2已经完成,结果std :: system_error被抛出。
However, this has the possibility to throw a std::system_error. Consider thread 1 calls thread2.joinable(), returns true, indicating that the thread2 is still running. Then the scheduler pauses thread1 and switches contexts to thread 2. Thread 2 completes, and then thread 1 resumes. Thread 1 calls thread2.join(), but thread2 has already completed, and as a result, std::system_error is thrown.
可能的解决方案是将整个一个尝试块中的东西:
A possible solution is to wrap the whole thing in a try block:
try {
thread2.join();
catch (std::system_error &e) {}
但是当一个合法的std :: system_error被抛出,可能表示线程无法加入,该程序继续,表现为一切都很好,很花园。除了使用这样的try / catch块,是否有正确的方法加入线程?
But then when a legitimate std::system_error is thrown, possibly to indicate that the thread failed to join, the program continues on, acting as though everything is fine and dandy. Is there a proper way to join a thread besides using a try/catch block like this?
推荐答案
可连接
不会做你认为的事情。 它是返回线程对象是否不与线程相关联。但是,如果线程对象也表示当前线程, thread :: join
将失败。因此,由于缺少 joinable
,因为 thread :: join
的唯一原因是如果您尝试加入自己
joinable
does not do what you think it does. All it does is return whether the thread object is not associated with a thread. However, thread::join
will fail if the thread object also represents the current thread. So the only reason for thread::join
to fail due to lack of joinable
is if you tried to join with yourself.
完成线程(不是您自己的)线程仍然完美连接。
A completed thread (which isn't your own) is still perfectly joinable.
这篇关于C ++ 11安全地加入线程,而不使用try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!