18.5 线程的销毁和多线程并发服务器的实现
2026/1/28大约 1 分钟
18.5 线程的销毁和多线程并发服务器的实现
销毁线程
相关信息
Linux 线程并不是在首次调用的线程main函数返回时自动销毁,用以下方式加以明确,否则由线程创建的内存空间将一直存在。
这里线程main函数 就是线程函数
明确销毁的方式:
- pthread_join( )
- phtread_detach( )
问:线程的销毁 和 线程的终止的区别?
终止:线程函数不会再被执行,线程的状态变为终止,但是线程本身仍然存在?
销毁:线程相关的内存被清理,线程本身不再存在?
参考Gemini
| 终止 | 销毁 | |
|---|---|---|
| 何时 | 自己:pthread_exit( ),return 被动:pthread_cancel( ), exit( ), main - return | pthread_join( ):阻塞等待线程终止,获取返回值后销毁 pthread_detach( ):终止后由系统自动销毁 |
| 占用内存 | “线程的栈空间、退出状态码。。。等资源仍然保留” | 不占用任何内存 - 已经清理、销毁 |
detach
NAME
pthread_detach - detach a thread
SYNOPSIS
#include <pthread.h>
int pthread_detach(pthread_t thread);
Compile and link with -pthread.
DESCRIPTION
The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are automatically released back to the system without the need for another thread to join with the terminated thread.
Attempting to detach an already detached thread results in unspecified behavior.- "调用该函数不会引起(指定的)线程终止 或 (导致调用该函数的线程)进入阻塞状态 "
- 不能对已经detach的线程再次调用 pthread_join
问:对于调用detach 时已经终止 和 尚未终止的线程,系统是如何进行回收的?
多线程并发服务器端的实现
略