线程分离 - 线程也会内存泄漏
-
线程退出后,释放了所有占用的资源嘛?
-
上述问题我们通过以下代码进行测试,不断地创建线程,每次创建线程计数器加一,直到创建线程失败,打印出已创建的线程数
#include <stdio.h> #include <unistd.h> #include <pthread.h> void *thread(void *arg) { } int main(int args, char *argv[]) { pthread_t tid = 0; int error_flag = 0; int thread_number = 0; while(0 == error_flag) { error_flag = pthread_create(&tid, NULL, thread, NULL); //pthread_detach(tid); //pthread_join(tid, NULL); thread_number++; //printf("thread_number is %d\n", thread_number); } printf("thread_number is %d\n", thread_number); printf("error_flag is %d\n", error_flag); return 0; }
-
编译
-
运行
-
注释21,22行代码(//pthread_detach(tid); //pthread_join(tid, NULL);),线程创建到3w多次失败
-
只注释22行代码(//pthread_join(tid, NULL);),线程一直在创建
-
只注释21行代码(//pthread_detach(tid);),线程一直在创建
-
21和22行都不注释,该情况在我https://blog.youkuaiyun.com/MOSHIWANGJUE/article/details/105856327线程实例5中已经测试,已经分离后的线程无法通过join得到退出状态。
-
-
-
由上述测试结果可知
-
线程创建时默认情况是非分离的,非分离线程再结束后,线程不会释放自身资源。如果没有将线程资源回收,将产生僵尸线程,当线程将进程的的虚拟空间占据完后,便会引发12号errno错误,无法申请内存。
-
非分离的线程终止后的退出信息会保存到pthread_join()显示回收后,否则一直保存到所在进程结束。
-
因此,我们在使用线程时,需要在将线程设置为分离态,或者使用join函数显示回收。
-
-
-
设置线程为游离态的两种方法
-
创建线程后使用detach进行分离,在创建完线程后,使用detach(tid)进行线程分离
-
创建线程前修改线程属性进行分离
-
代码实现如下
#include <stdio.h> #include <unistd.h> #include <pthread.h> int main(void) { pthread_t tid; void *tret; int err; #if 1 pthread_attr_t attr; /*通过线程属性来设置游离态*/ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&tid, &attr, tfn, NULL); #else pthread_create(&tid, NULL, tfn, NULL); pthread_detach(tid); //让线程分离 ----自动退出,无系统残留资源 #endif while (1) { err = pthread_join(tid, &tret); printf("-------------err= %d\n", err); if (err != 0) fprintf(stderr, "thread_join error: %s\n", strerror(err)); else fprintf(stderr, "thread exit code %d\n", (int)tret); sleep(1); } return 0; }
-