问题描述
有时候我必须使用 std :: thread
来加快我的应用程序。我也知道 join()
等待,直到线程完成。这很容易理解,但是调用 detach()
和不调用它有什么区别?
Sometime I have to use std::thread
to speed up my application. I also know join()
waits until a thread completes. This is easy to understand, but what's the difference between calling detach()
and not calling it?
没有 detach()
,线程的方法将独立使用线程。
I thought that without detach()
, the thread's method will work using a thread independently.
不分离:
void Someclass::Somefunction()
{
//...
std::thread t([ ] {
printf("hello, this is thread calling without detach!");
});
//some code here
}
:
void Someclass::Somefunction()
{
//...
std::thread t([ ] {
printf("hello, this is thread calling with detach!");
});
t.detach();
//some code here
}
推荐答案
在 std :: thread
, std :: terminate
如果
- 线程未加入(
t.join()
) - 且未分离(使用
t.detach()
)
- the thread was not joined (with
t.join()
) - and was not detached either (with
t.detach()
)
因此,你应该总是 join
或 detach
当程序终止时(即 main
返回)在后台执行的剩余的分离线程不等待;
When a program terminates (ie, main
returns) the remaining detached threads executing in the background are not waited upon; instead their execution is suspended and their thread-local objects destructed.
重要的是,这意味着这些线程的堆栈没有解开,因此它们的线程本地对象被破坏。一些析构函数不会被执行。根据破坏者应该采取的行动,这可能就像程序崩溃或被杀害一样糟糕。希望操作系统将释放文件上的锁等等,但你可能已损坏的共享内存,半文件等。
Crucially, this means that the stack of those threads is not unwound and thus some destructors are not executed. Depending on the actions those destructors were supposed to undertake, this might be as bad a situation as if the program had crashed or had been killed. Hopefully the OS will release the locks on files, etc... but you could have corrupted shared memory, half-written files, and the like.
那么,你应该使用 join
还是分离
?
So, should you use join
or detach
?
- 使用
加入
- 除非您需要更多的灵活性,以提供自己等待线程完成的同步机制,在这种情况下您可以使用
分离
- Use
join
- Unless you need to have more flexibility AND are willing to provide a synchronization mechanism to wait for the thread completion on your own, in which case you may use
detach
这篇关于什么时候应该使用std :: thread :: detach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!