linux 线程编程:线程终止

来源:互联网 发布:mac 百度云下载太慢 编辑:程序博客网 时间:2024/04/30 12:57

今天写一下关于线程终止、资源回收释放的内容:

线程终止

终止线程的可能方式有:

显示调用pthread_exit(void *rval_ptr);

显示调用return (void *)retcode;

线程没有调用任何退出函数,执行完,隐式终止; 

其他线程取消该线程(后面再讨论)而终止;

其他可能导致线程异常的终止。

(注意,不能再线程中调用exit()以及其他相似的函数,否则整个进程都会被终止)!

资源回收释放

资源回收释放包括两部分内容:

一,内核维护的资源,需要调用pthread_join(pthread_t thread,  void **rval_ptr);回收线程资源(非分离状态),否则需要将线程设置为分离状态。

二,线程中malloc等动态获取的资源,线程终止前需要调用free等函数将资源释放,否则造成内存泄露,或者其他资源得不到释放。

相关函数

#include <pthread.h>
int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, (void*)(*start_rtn)(void*), void *arg);
int pthread_join(pthread_t thread, void **retval);
void pthread_cleanup_push(void (*rtn)(void *),void *arg);
void pthread_cleanup_pop(int execute);
int pthread_detach(pthread_t tid);
pthread_t pthread_self(void);

测试代码

#include <stdio.h>#include <stdlib.h>#include <pthread.h>void *pfunc(void *arg);void clean_func(void *arg);int main(int argc, char **argv){int ret = -1;pthread_t tid;ret = pthread_create(&tid, NULL, pfunc, NULL);if(0 != ret){printf("[%s:%d] create pthread fail\n", __func__, __LINE__);}ret = pthread_join(tid, NULL);if(0 != ret){printf("[%s:%d] pthread join fail\n", __func__, __LINE__);}return 0;}void *pfunc(void *arg){//pthread_detach(pthread_self()); //调用该函数可以将线程设置为分离状态,否则需要调用pthread_join来回收资源.unsigned char *tmp = malloc(sizeof(unsigned char)*8);if(NULL == tmp){printf("[%s:%d] malloc fail\n", __func__, __LINE__);pthread_exit(NULL);}pthread_cleanup_push(clean_func, tmp);pthread_exit(NULL); //模拟线程异常退出.//return (void*)0;  //return 退出线程,不会调用clean_func.if(tmp){free(tmp);tmp = NULL;printf("[%s:%d] free ok\n", __func__, __LINE__);}pthread_cleanup_pop(0); //弹出并且不执行clean_func函数.//exit(0); //线程中不能调用该函数,或者类似函数,否则整个进程都会终止.//return (void*)0;pthread_exit(NULL);}void clean_func(void *arg){if(arg){free((unsigned char *)arg);printf("[%s:%d] clean free ok\n", __func__, __LINE__);}}
运行结果

[clean_func:61] clean free ok


0 0
原创粉丝点击