【Linux系统编程】线程_01_线程基本API_06_线程清理cleanup_push&cleanup_pop

1.pthread_cleanup_push

  1. 功能:清理函数
  2. 原型
void pthread_cleanup_push(void (*routine)(void *), void *  arg);
  1. 参数
    1)void (*routine) (void*)
    执行:
    a.显式调用:pthread_exit
    b.线程被取消:pthread_cancel
    c.清理处理函数被弹出:pthread_cleanup_pop(1),\会立刻执行相应的清理函数,但线程暂未被终止,直到 pthread_exit() 或 start_routine 返回
    2)void* args
  2. 返回值
    无返回值

2.pthread_cleanup_pop

  1. 功能:清理函数
  2. 原型
void pthread_cleanup_pop(int execute);
  1. 参数
    1)int execute:0,不执行;非0,执行
  2. 返回值
    无返回值

执行时机
1)调用 pthread_exit()
2)响应取消请求
3)调用 pthread_cleanup_pop(1),不会导致线程终止

注意事项
1)从 start_routine 正常返回,不会执行线程清理函数(不会被自动调用,例:return NULL;)
2)pthread_cleanup_push 和 pthread_cleanup_pop 必须成对出现

DO

#include <func.h>

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

void* start_routine(void* args) {
    // 注册线程清理函数
    pthread_cleanup_push(cleanup, "first");
    pthread_cleanup_push(cleanup, "second");
    pthread_cleanup_push(cleanup, "third");

    // pthread_cleanup_pop(1);
    // pthread_cleanup_pop(0);

    sleep(2);

    printf("thread1: I'm going to die...\n");
    
    pthread_exit(NULL);     // 子线程退出
    // return NULL;
    
    // while (1) {
    //     pthread_testcancel();
    // }
    // 后面的代码肯定不会被执行

    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
}

int main(int argc, char* argv[])
{
    pthread_t tid;

    int err;
    err = pthread_create(&tid, NULL, start_routine, NULL);
    if (err) {
        error(1, err, "pthread_create");
    }

    sleep(3);
    pthread_cancel(tid); // 给tid发送取消请求

    // 等待子线程结束
    err = pthread_join(tid, NULL);
    if (err) {
        error(1, err, "pthread_join %lu", tid);
    }
    return 0;
}

相关推荐

  1. linux系统编程 线 p1

    2024-06-19 00:00:04       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-19 00:00:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-19 00:00:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-19 00:00:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-19 00:00:04       18 阅读

热门阅读

  1. 平移矩阵中的数学思考

    2024-06-19 00:00:04       8 阅读
  2. Spring Cloud Gateway 概述与基本配置(上)

    2024-06-19 00:00:04       7 阅读
  3. 从零学习es8

    2024-06-19 00:00:04       6 阅读
  4. Stage模型

    2024-06-19 00:00:04       6 阅读
  5. 正规式理解

    2024-06-19 00:00:04       5 阅读
  6. 一文看懂E2PROM、FLASH等芯片,软件开发

    2024-06-19 00:00:04       6 阅读