首页 > 编程语言 > 详细

多线程之清理线程

时间:2021-04-20 15:59:11      阅读:29      评论:0      收藏:0      [点我收藏+]

我们最希望的就是线程在退出的时候释放其所占的所有资源,并且释放其设置的一些类似锁的资源,这就要求我们在退出线程的时候必须有收尾的操作,即线程退出时的清理

1. 清理函数

  1) void pthread_cleanup_push(void (*routine) (void*), void *arg)

  routine: 清理函数的函数指针

  arg: 清理函数的实参

  2) void pthread_cleanup_pop(int execute)

  execute:弹出清理函数时是否执行, 0不执行, 非0 执行

  注意点:

  1. 这两个函数在同一个函数中必须成对存在

  2. 清理函数得到执行的情况如下:

    • 线程主动结束,pthread_exit()
    • pthread_cancel()取消该线程
    • pthread_clean_pop(1)  执行该函数 并且和参数不为0

 2. 代码举例子----线程被动取消

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void clean_fun(void *arg)
{
    printf("I am a clean function\n");
    return;
}

void *pth_fun(void *arg)
{    
    pthread_cleanup_push(clean_fun, NULL)
    printf("I am a pthread function\n");
    while (1) {
        pthread_testcancel();
    }
    pthread_cleanup_pop(0); 
    return NULL;
}
int main(void)
{
    pthread_t pth;
    int res = pthread_create(&pth, NULL, pth_fun, NULL);
    if (res) {
        printf("create pthread error!\n");
        return 0;
    }
    sleep(3);
    res = pthread_cancel(pth);
    pthread_join(pth, NULL);
    printf("hello world!\n");
    return 0;
}

3. 线程主动结束

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void clean_fun(void *arg)
{
    printf("I am a clean function\n");
    return;
}

void *pth_fun(void *arg)
{    
    pthread_cleanup_push(clean_fun, NULL)
    printf("I am a pthread function\n"); 
    pthread_exit(0);
    // return (void*)0; // 无法触发清理函数的执行
    pthread_cleanup_pop(0);
}
int main(void)
{
    pthread_t pth;
    int res = pthread_create(&pth, NULL, pth_fun, NULL);
    if (res) {
        printf("create pthread error!\n");
        return 0;
    }
    sleep(3);
    //pthread_join(pth, NULL);
    printf("hello world!\n");
    return 0;
}

 

多线程之清理线程

原文:https://www.cnblogs.com/victor1234/p/14680890.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!