线程退出的几种方式和资源回收【线程编程中避免内存泄漏】

线程退出油多种方式,如return,pthread_exit,pthread_cancel等;线程分为可结合的(joinable)和 分离的(detached)两种,如果没有在创建线程时设置线程的属性为PTHREAD_CREATE_DETACHED,则线程默认是可结合的。可结合的线程在线程退出后不会立即释放资源,必须要调用pthread_join来显式的结束线程。分离的线程在线程退出时系统会自动回收资源。

一、设置分离线程的几种方法:

1.在创建线程时加上

pthread_attr_t attr;
pthread_t thread;
pthread_attr_init (&attr);pthread_attr_setdetachstat(&attr, PTHREAD_CREATE_DETACHED);
pthread_create (&thread, &attr, &thread_function, NULL);
pthread_attr_destroy (&attr);
2.在线程中调用pthread_detach(pthread_self());

3.主线程中调用pthread_detach(pid),pid为子线程的线程号

要注意的是,设置为分离的线程是不能调用pthread_join的,调用后会出错

二、可结合的线程的几种退出方式

1. 子线程使用return退出,主线程中使用pthread_join回收线程

2.子线程使用pthread_exit退出,主线程中使用pthread_join接收pthread_exit的返回值,并回收线程

3.主线程中调用pthread_cancel,然后调用pthread_join回收线程

楼主亲测使用pthread_join回收线程一万次,未出现内存占用增加的现象,因此反复创建线程时出现Cannotallocate memory ,应该是有些线程没有被join,并不是pthread_join没有回收资源。


相关资料:在 POSIX 线程编程中避免内存泄漏:http://www.ibm.com/developerworks/cn/linux/l-memory-leaks/

http://blog.chinaunix.net/uid-29924858-id-4603600.html

原文地址:https://www.cnblogs.com/feng9exe/p/8340550.html