运行线程和线程对象之间的关系

Relation between running Thread and the thread object

本文关键字:线程 关系 之间 对象 运行      更新时间:2023-10-16

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

启动线程后,您需要明确决定是否 等待它完成(通过加入它 - 请参阅第 2.1.2 节(或 让它独立运行(通过分离它 - 参见第 2.1.3 节(。如果你 在 std::thread 对象被销毁之前不要决定,然后你的 程序终止(std::线程析构函数调用 std::terminate(((.因此,您必须确保 螺纹正确连接或分离,即使存在 异常。有关处理此方案的技术,请参见第 2.1.3 节。 请注意,您只需要在 std::thread 之前做出此决定 对象被销毁 - 线程本身很可能已经完成很长时间 在加入或分离它之前,如果您分离它,则 线程可能会在 std::thread 对象 摧毁。

即使在线程对象被销毁后,线程何时运行?有人有示例代码或任何参考吗?

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

所以下面的代码:

#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 stuffrn";
});
thr.detach();
} //thr is destroyed here
std::cout << "thr destroyed, start sleeprn";
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "sleep overrn";
}

将输出:

thr destroyed, start sleep
Thread stuff
sleep over