多线程pthread使用时资源释放两种方法:
1、使用pthread_join
#include <stdio.h>
#include <pthread.h>
void *add1()
{
//pthread_detach(pthread_self());
printf("AAAAA\n");
pthread_exit(NULL);
return;
}
int main()
{
int i = 0;
for(i = 0; i < 100; i++)
{
pthread_t t1 = 0;
pthread_create(&t1, NULL, add1, NULL);
sleep(1);
pthread_join(t1, NULL);
}
return;
}
2、使用pthread_detach(pthread_self());
#include <stdio.h>
#include <pthread.h>
void *add1()
{
pthread_detach(pthread_self());
printf("AAAAA\n");
pthread_exit(NULL);
return;
}
int main()
{
int i = 0;
for(i = 0; i < 100; i++)
{
pthread_t t1 = 0;
pthread_create(&t1, NULL, add1, NULL);
sleep(1);
//pthread_join(t1, NULL);
}
return;
}
pthread_detach()使主线程与子线程分离,两者相互不干涉,子线程结束的同时子线程的资源由系统自动回收。
pthread_join()即是子线程合入主线程,主线程会一直阻塞,直到子线程执行结束,然后回收子线程资源,并继续执行。
所以每个进程创建以后都应该调用pthread_join 或 pthread_detach 函数,只有这样在线程结束的时候线程的独有资源(线程的描述信息和stack)才能被释放,不然必会造成内存泄漏。
参考:https://blog.csdn.net/qq_35721743/article/details/86717509