【发布时间】:2017-06-12 17:32:26
【问题描述】:
当我创建一个 std::thread 实例时,它什么时候会被销毁?线程完成任务的时间是被销毁还是作为普通对象工作,当它不再使用时将被销毁?
//a fake function for std::thread
void func();
void main()
{
auto threadPtr = std::make_shared<std::thread>(func)
threadPtr->join();
// is thread object which threadPtr point destructed in here ?
//... other stuffs ....
}
threadPtr->join()之后线程对象是否被破坏?
【问题讨论】:
-
没有其他代码共享该线程实例,所以如果它只是在堆栈上分配,它只是一样的。
-
你认为线程对象为什么被破坏了?
-
threadPtr在您离开 main 时被销毁,就像任何其他堆栈变量一样。 -
所以 std::thread 对象将被销毁为普通对象。它完成任务后不会被破坏,对吗?
-
@buddha “它完成任务不会被破坏,对吗?” 没错!
标签: c++ multithreading shared-ptr stdthread