线程退出前操作

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

void cleanup()
{
    printf("cleanup
");
}

void *test_cancel(void)
{
    pthread_cleanup_push(cleanup,NULL);
    printf("test_cancel
");

    while(1)
    {
        printf("test message
");
        sleep(1);
    }
    pthread_cleanup_pop(0);
}
int main()
{
    pthread_t tid;
    pthread_create(&tid,NULL,(void *(*)(void *))test_cancel,NULL);
    sleep(2);
    pthread_cancel(tid);
    pthread_join(tid,NULL);
    return 0;
}

原文地址:https://www.cnblogs.com/lakeone/p/3789274.html