UNIX(编程-线程处理):05---线程退出清理函数(pthread_cleanup_push、pthread_cleanup_pop)

 一、函数介绍

#include <pthread.h>
void pthread_cleanup_push(void (*rtn)(void *), void *arg);
void pthread_cleanup_pop(int execute);

实现原理:

  •  pthread_cleanup_push:向栈中注册一个线程退出清理函数。因此先调用的pthread_cleanup_push函数后执行。并且pthread_cleanup_push函数可以设置多个
  • pthread_cleanup_pop:如果参数为0,就删除一个栈顶注册的线程退出清理函数。(注意:调用一次只清理一个)

 pthread_cleanup_push:

当线程执行下列动作时,pthread_cleanup_push函数就会执行参数1所指向的函数,并且参数1所指的函数的参数就是参数2

  • 调用 pthread_exit 时
  • 响应取消请求时
  • 用非零execute参数调用pthread_cleanup_pop时

重点:如果不是上面3中情况(例如在线程中return等),pthread_cleanup_push函数就不会执行

pthread_cleanup_pop:

  • 如果参数为0,用来删除上一次栈内注册的线程退出清理函数

这两个函数的限制:

  • 由于他们可以实现为宏,所以必须在与线程相同的作用域中以匹配对的形式使用.pthread_cleanup_push的宏可以包含字符 {, 这种情况下,在 pthread_cleanup_pop 的定义中要有对应的匹配字符 }

 二、演示案例

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

void cleanup(void *arg){
    printf("cleanup: %s\n", (char *)arg);
}

void *thr_fn1(void *arg){
    printf("thread 1 start...\n");

    pthread_cleanup_push(cleanup, "thread 1 first handler");
    pthread_cleanup_push(cleanup, "thread 1 second handler");
    printf("thread 1 push complete\n");

    if (arg) {
        return ((void*)1);
    }

    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);

    return ((void *)1);
}

void *thr_fn2(void *arg){
    printf("thread 2 start...\n");
    pthread_cleanup_push(cleanup, "thread 2 first handler");
    pthread_cleanup_push(cleanup, "thread 2 second handler");
    printf("thread 2 push complete\n");

    if (arg) {
        pthread_exit((void*)2);
    }

    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);

    pthread_exit((void*)2);
}

int main(void)
{
    int err;
    pthread_t tid1, tid2;
    void *tret;

    err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);//创建线程1
    if (err != 0) {
        printf("Can't create thread 1\n");
        exit(0);
    }
    err = pthread_create(&tid2, NULL, thr_fn2, (void *)1);//创建线程2
    if (err != 0) {
        printf("Can't create thread 2\n");
        exit(0);
    }

    err = pthread_join(tid1, &tret);//等到线程1
    if (err != 0) {
        printf("Can't join with thread 1\n");
        exit(0);
    }
    printf("thread 1 exit code: %ld\n", (long)tret);

    err = pthread_join(tid2, &tret);//等待线程2
    if (err != 0) {
        printf("Can't join with thread 2\n");
        exit(0);
    }
    printf("thread 2 exit code: %ld\n", (long)tret);

    exit(0);
}

运行结果

猜你喜欢

转载自blog.csdn.net/qq_41453285/article/details/89307166