运行线程和线程对象之间的关系
Relation between running Thread and the thread object
在学习基本的线程管理时,我发现很难从书中理解这些行(粗体(。
启动线程后,您需要明确决定是否 等待它完成(通过加入它 - 请参阅第 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
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 运行线程和线程对象之间的关系
- Qt:工作线程和 GUI 事件之间的关系
- OpenMP 并行编程基于线程数与执行时间的关系
- 原子线程围栏:为什么在这个非原子变量上存在数据竞争?这有关系吗
- 块的一些线程达到__syncthreads(),而其中一些线程没有达到,这有关系吗