[英]What happens with unjoined and not detached threads when the whole process terminates?
It is expected that threads, on which pthread_detach()
was not called, should be pthread_join()
ed before the main thread returns from main()
or calls exit()
. 预计线程,其上
pthread_detach()
不叫,应该pthread_join()
主线程返回之前版main()
或调用exit()
However, what happens when this requirement is not met? 但是,如果不满足此要求怎么办? What happens when a process terminates when it still contains unjoined and not detached threads?
当进程仍然包含未连接且未分离的线程时终止该进程会发生什么?
I would find it odd to learn that these other threads' resources will not be reclaimed until system reboot. 我会发现奇怪的是,在系统重新启动之前,其他线程的资源不会被回收。 However, if these resources will be reclaimed, then there may be little need to bother about joining or detaching, mightn't it?
但是,如果将这些资源回收,那么可能几乎不需要费心加入或分离,不是吗?
It is up to the operating system. 这取决于操作系统。 Typical modern operating systems will indeed reclaim the memory and descriptors (handles) used by abandoned threads.
典型的现代操作系统确实会回收废弃线程使用的内存和描述符(句柄)。 This is similar to how dynamically allocated memory works: typical modern systems will reclaim it when a process exits, even if the process never explicitly freed the memory.
这类似于动态分配的内存的工作方式:典型的现代系统会在进程退出时回收它,即使进程从未显式释放内存。 For certain unusual programs, this can be a meaningful performance optimization, because freeing lots of small resources takes time and the OS may be able to do it more quickly.
对于某些不寻常的程序,这可能是有意义的性能优化,因为释放大量小资源需要时间,并且操作系统可能能够更快地完成此操作。
However, what happens when this requirement is not met?
但是,如果不满足此要求怎么办? What happens when a process terminates when it still contains unjoined and not detached threads?
当进程仍然包含未连接且未分离的线程时终止该进程会发生什么?
On any system with POSIX threads that is not ancient, the non-joined threads simply "evaporate" into space when the SYS_exit
system call is performed by the main thread. 在没有POSIX线程的任何较
SYS_exit
系统上,当主线程执行SYS_exit
系统调用时,未连接的线程只是简单地“蒸发”到空间中。
I would find it odd to learn that these other threads' resources will not be reclaimed until system reboot.
我会发现奇怪的是,在系统重新启动之前,其他线程的资源不会被回收。
They will be. 他们会。
However, if these resources will be reclaimed, then there may be little need to bother about joining or detaching, mightn't it?
但是,如果将这些资源回收,那么可能几乎不需要费心加入或分离,不是吗?
It depends on what these threads do. 这取决于这些线程的功能。 The danger is at-exit data races.
危险在于出口数据竞赛。
In C++
, global variables are destructed (usually via atexit
or equivalent registration mechanism), FILE
handles are deleted, etc. etc. 在
C++
,销毁全局变量(通常通过atexit
或等效的注册机制),删除FILE
句柄等,等等。
If non-joined thread tries to access any such resource, it will likely crash with SIGSEGV
, possibly producing core
dump, and an unclean process exit code, both of which are often quite undesirable. 如果未连接的线程尝试访问任何此类资源,则可能会因
SIGSEGV
崩溃,从而可能产生core
转储以及不干净的进程退出代码,这两者通常都是非常不希望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.