Linux 分离与可连接 POSIX 线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3756882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detached vs. Joinable POSIX threads
提问by
I've been using the pthread
library for creating & joining threads in C.
我一直在使用该pthread
库在 C 中创建和加入线程。
When should I create a thread as detached, right from the outset? Does it offer any performance advantage vs. a joinable thread?
Is it legal to not do a
pthread_join()
on a joinable (by default) thread? Or should such a thread always use thedetach()
function beforepthread_exit()
ing?
我什么时候应该从一开始就创建一个分离的线程?与可连接线程相比,它是否提供任何性能优势?
不在
pthread_join()
可连接(默认情况下)线程上执行 a 是否合法?或者这样的线程应该总是detach()
在pthread_exit()
ing之前使用该函数?
采纳答案by Jonathan Leffler
Create a detached thread when you know you won't want to wait for it with
pthread_join()
. The only performance benefit is that when a detached thread terminates, its resources can be released immediately instead of having to wait for the thread to be joined before the resources can be released.It is 'legal' not to join a joinable thread; but it is not usually advisable because (as previously noted) the resources won't be released until the thread is joined, so they'll remain tied up indefinitely (until the program exits) if you don't join it.
当您知道不想使用
pthread_join()
. 唯一的性能优势是当一个分离的线程终止时,它的资源可以立即释放,而不必等待线程加入才能释放资源。不加入可连接的线程是“合法的”;但通常不建议这样做,因为(如前所述)在加入线程之前不会释放资源,因此如果您不加入它,它们将无限期地保持绑定状态(直到程序退出)。