线程的资源回收:pthread_detach与pthread_cleanup_push/pthread_cleanup_pop的组合

线程退出

单个线程可以通过3种方式退出,因此可以在不终止整个进程的情况下,停止它的控制流。
1)线程可以简单地执行完后结束,返回值是线程的退出码。
2)线程可以被同一进程中的其他线程用pthread_cancel所取消。
3)线程调用pthread_exit。

线程退出时需要回收资源,一方面回收线程本身的资源,另一方面还需要回收线程使用的特殊资源,例如互斥锁(回收互斥锁,也就是解锁),malloc开辟的空间。

线程资源pthread_detach与pthread_cleanup_push/pthread_cleanup_pop的组合的回收模板:

/*创建线程*/
pthread_create(&threadID, NULL, cam_thread, in);/*in会传给cam_thread*/
pthread_detach(pctx->threadID);/*即主线程与子线程分离,两者相互不干涉,子线程结束同时子线程的资源自动回收。*/


/*cam_thread的函数实现*/
void cam_thread(){

    pthread_cleanup_push(cleanup, NULL);

    /*do some work*/
    if (某些函数的返回值出现异常,比如打开某文件失败)
       {
            goto endloop;
    }
endloop:           /*就算没有出现异常 最终也要通过指令跳转到endloop*/
    pthread_cleanup_pop(1);
    return NULL;   /*执行完return之后,线程自然退出,此时由于是分离线程,线程自动完成本身资源回收*/
}


void cleanup(void *arg)
{
    input * in = (input*)arg;
    context *pctx = (context*)in->context;
    
    IPRINT("cleaning up resources allocated by input thread\n");

    if (pctx->videoIn != NULL) {
        close_v4l2(pctx->videoIn);
        free(pctx->videoIn->tmpbuffer);
        free(pctx->videoIn);
        pctx->videoIn = NULL;
    }
    
    free(in->buf);
    in->buf = NULL;
    in->size = 0;
}
/* !!!!!   */
/*值得注意是  如果遇到ctrl+c 需要在main里面加入 signal (SIGINT, ReleaseResource);  
进行一些资源的释放*/

!!!!! 
值得注意是  如果遇到ctrl+c 需要在main里面加入 signal (SIGINT, ReleaseResource);  
进行一些资源的释放

参考文章:

1:Linux线程的创建与回收_linux线程自己跑完会释放吗-CSDN博客

补充上述文章:

回收线程 pthread_join 阻塞函数   pthread_tryjoin_np 非阻塞函数;

2:pthread_cleanup_push()/pthread_cleanup_pop()的详解-CSDN博客

Linux 线程控制 —— 线程清理 pthread_cleanup_push-CSDN博客

注意 : pthread_cleanup_push/pthread_cleanup_pop 如果使用exit 或cancel 退出,pthread_cleanup_pop() 的参数要选为0

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2023-12-15 10:52:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-15 10:52:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-15 10:52:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-15 10:52:05       20 阅读

热门阅读

  1. 力扣labuladong——一刷day74

    2023-12-15 10:52:05       38 阅读
  2. filecmp --- 文件及目录的比较

    2023-12-15 10:52:05       37 阅读
  3. mysql binlog_ignore_db参数的效果详解

    2023-12-15 10:52:05       36 阅读
  4. 9月7日算法学习笔记(栈)

    2023-12-15 10:52:05       34 阅读
  5. 力扣面试150题 |有效的括号

    2023-12-15 10:52:05       49 阅读
  6. LintCode 123 · Word Search (DFS字符处理经典题!)

    2023-12-15 10:52:05       38 阅读
  7. c#面试基础语法——as和is的区别

    2023-12-15 10:52:05       40 阅读
  8. RT-1配置文件

    2023-12-15 10:52:05       31 阅读
  9. 【前端设计模式】之享元模式

    2023-12-15 10:52:05       39 阅读
  10. vue混入、路由、动态路由匹配

    2023-12-15 10:52:05       41 阅读
  11. HTML5结构规范

    2023-12-15 10:52:05       35 阅读
  12. 浏览器 css 默认的字体图表

    2023-12-15 10:52:05       37 阅读