C ++ 11安全地加入一个线程,而不使用try / catch块 [英] C++11 safely join a thread without using a try / catch block

查看:115
本文介绍了C ++ 11安全地加入一个线程,而不使用try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档此处在这里,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(),但是thread2已经完成,因此,抛出了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.

一个可能的解决方案是包装整个try块中的内容:

A possible solution is to wrap the whole thing in a try block:

try {
    thread2.join();
catch (std::system_error &e) {}

std :: system_error被抛出,可能表明线程未能加入,程序继续,表现为一切都很好,dandy。除了使用这样的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?

推荐答案

joinable 不会做你认为它。 是返回线程对象是否与线程没有关联。但是,如果线程对象也代表当前线程, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆