linux C线程退出回调函数

待补充....................

函数原型

void pthread_cleanup_push(void (*routine)(void*), void *arg);
void pthread_cleanup_pop(int execute);//这里的int参数,0是不执行push的内容,非0是执行。

三种情况触发回调函数:

    1、调用pthread_cancel()删除线程。

    2、调用ptread_exit()推出线程。

    3、调用pthread_cleanup_pop(1)时参数不为0。


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

pthread_t thread1, thread2;

void cleanUp(void * arg)//线程清理回调函数
{
    printf("%s\n", "cleanUp");
}

void * thread1Func(void *arg)线程一
{
    pthread_cleanup_push(cleanUp, "this is cleanUp")
    printf("%s\n","sadf");

    sleep(4);
    pthread_cleanup_pop(0);      //一定要在调用pthread_exit()函数 之前调用pthread_cleanup_pop()函数,cleanup函数才能被调用,因为pop弹出之前才能被调用嘛
    pthread_exit((void *)1);//无法触发回调cleanup
}

void * thread2Func(void *arg)
{
    pthread_cleanup_push(cleanUp, "this is cleanUp")
    printf("%s\n","sadf");

    sleep(4);

    pthread_exit(0);//触发回调cleanup
    pthread_cleanup_pop(0);    
}

int main()
{
    pthread_create(&thread1, NULL, (void *)thread1Func, NULL);
    pthread_create(&thread2, NULL, (void *)thread2Func, NULL);
    sleep(1);
    pthread_cancel(thread1);//触发回调
    pthread_cancel(thread2);//触发回调
    sleep(4);
    // pthread_join(thread1,NULL);
    // pthread_join(thread2,NULL);

    return 0;
}




转载于:https://my.oschina.net/u/2255341/blog/542101

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值