
我一直以为程序会创建一个线程,线程运行后线程会自动清除资源.
项目中最近使用的线程,除了业务逻辑,我将其简化为这样
//pthread.c 错误demo示例
#include <stdio.h>
#include <pthread.h>
static int testcount = 0;
static void *test_thread_handler()
{
testcount++;
printf("%d\n",testcount);
return 0;
}
int main( int argc, char *argv[] )
{
int ret = 0;
pthread_t test_tid;
while(1)
{
usleep(10000);
ret = pthread_create(&test_tid, NULL, test_thread_handler,NULL);
if(ret != 0)
{
printf("Create handler error :%d!\t testcount:%d\n", ret, testcount);
return -1;
}
}
return 0;
}

备注: pthread库不是Linux系统的默认库. 连接时需要使用静态库libpthread.a,因此在编译线程函数时,需要连接库函数
gcc pthread.c -o pthread -lpthread
结果如下

最终数量在不同的计算机上不同,但是结果应该相同.
pthread_create()11返回的错误代码表示资源暂时不可用

该资源暂时不可用. 完全有理由程返回0后自动释放资源. 与此同时,我使用free发现内存也足够.
在以多种方式搜索信息之后,我了解到linux线程执行与Windows不同. pthread具有两种状态: 可连接状态和不可连接状态. 默认状态为可连接.
如果线程处于可连接状态,则当线程函数返回退出状态或pthread_exit不会释放该线程占用的堆栈和线程描述符(总计超过8K)时,其状态类似于Zombie Process中的进程(僵尸进程)). 这些资源只会在调用pthread_join之后释放.

如果它是不可连接的线程,则程函数退出或pthread_exit时pthread create返回值,这些资源将自动释放.
但是在调用pthread_join(pthread_id)之后,如果线程未完成,则调用者将被阻止. 如果不需要阻止,则可以在此时将代码添加到子线程
pthread_detach(pthread_self())
或父线程调用
pthread_detach(test_tid)(非阻塞pthread create返回值,可以立即返回)
这会将子线程的状态设置为“已分离”,然后程运行后将自动释放所有资源.
最终过程如下:
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-240688-1.html
不惜一战
用以练手
用魚雷小艇和炮艇