【问题标题】:C++11 safely join a thread without using a try / catch blockC++11 在不使用 try / catch 块的情况下安全地加入线程
【发布时间】:2013-04-06 08:32:03
【问题描述】:

根据文档herehere,如果joinable() == false,C++11 线程的join 方法将抛出std::system_error。因此,等待线程完成执行的自然方式是:

if (thread2.joinable()) thread2.join();

但是,这有可能引发 std::system_error。考虑线程1调用thread2.joinable(),返回true,说明thread2还在运行。然后调度程序暂停线程 1 并将上下文切换到线程 2。线程 2 完成,然后线程 1 恢复。线程1调用thread2.join(),但是thread2已经完成,结果抛出std::system_error。

一个可能的解决方案是将整个东西包装在一个 try 块中:

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

但是当一个合法的 std::system_error 被抛出时,可能表明线程未能加入,程序继续运行,表现得好像一切都很好。除了使用这样的 try/catch 块之外,还有其他合适的方法来加入线程吗?

【问题讨论】:

    标签: c++ multithreading exception c++11 exception-handling


    【解决方案1】:

    joinable 并没有按照你的想法去做。 所有 它所做的是返回线程对象是否与线程相关联。但是,如果线程对象也代表当前线程,thread::join 将失败。因此,thread::join 因缺少joinable 而失败的唯一原因是您尝试加入自己。

    已完成线程(不是您自己的)仍然可以完美连接。

    【讨论】:

    • 如果线程分离,joinable 也将返回 false
    • @Adam:感谢您阐明“与线程无关”的真正含义。
    • return whether the thread object represents the current thread or is not associated with a thread joinable检查与线程的关联,但不检查与当前线程的关联。 但是 join 会检查当前线程并报告system_errorlive 例子。
    猜你喜欢
    • 2016-08-18
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多