【问题标题】:Relation between running Thread and the thread object运行线程与线程对象的关系
【发布时间】:2018-01-24 01:53:01
【问题描述】:

在学习基本线程管理时,我发现很难理解书中的这些行(粗体)。

一旦你开始了你的话题,你需要明确地决定是否 等待它完成(通过加入它——参见第 2.1.2 节)或 让它自己运行(通过分离它——参见第 2.1.3 节)。如果你 在 std::thread 对象被销毁之前不要决定,那么你的 程序终止(std::thread 析构函数调用 标准::终止())。因此,您必须确保 螺纹正确连接或分离,即使存在 例外。有关处理这种情况的技术,请参见第 2.1.3 节。 请注意,您只需在 std::thread 之前做出此决定 对象被销毁——线程本身很可能已经完成了很长时间 在加入或分离它之前,如果你分离它,那么 线程可能会在 std::thread 对象之后继续运行很长时间 销毁。

线程对象被销毁后,线程何时运行?谁有示例代码或任何参考?

【问题讨论】:

  • { std::thread th(SomeLongRunningFunction); th.detach(); /* th is destroyed here, but SomeLongRunningFunction continues to run on the worker thread */ }
  • 分离后,线程与std::thread对象无关。
  • 规则很简单:一个线程一直运行直到它从入口函数返回,或者它所属的可执行文件终止。
  • 线程object是程序在运行线程上的句柄。如果程序不需要join() 线程,或者在启动线程后对线程做任何事情,那么就不需要保留线程对象。在这种情况下,程序可以分离线程并销毁对象。

标签: c++ multithreading c++11 concurrency


【解决方案1】:

这意味着线程的生命周期与线程对象的生命周期无关。

所以下面的代码:

#include <thread>
#include <iostream>

int main() {
    { //scope the thread object
        std::thread thr = std::thread([]() {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::cout << "Thread stuff\r\n";
        });
        thr.detach();
    } //thr is destroyed here
    std::cout << "thr destroyed, start sleep\r\n";
    std::this_thread::sleep_for(std::chrono::seconds(10));
    std::cout << "sleep over\r\n";
}

将输出:

thr destroyed, start sleep
Thread stuff
sleep over

【讨论】:

  • 这是一个可能的输出。 “线程的东西”可能首先出现。
  • @Hi 什么时候会这样?
  • 该标准不保证线程何时启动。它只是说在创建时它将被安排启动。实际运行线程取决于操作系统。唯一的保证是连接会一直等到线程完成,但由于它是分离的,我们不能使用连接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 2018-09-27
  • 2019-09-30
  • 1970-01-01
  • 2016-09-02
相关资源
最近更新 更多