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;
}




你可能感兴趣的:(linuxC线程,线程回调函数)