C++多线程之——pthread_cleanup_push与pthread_cleanup_pop

pthread_cleanup_push 是 POSIX 线程库中的一个宏(macro),用于设置线程清理函数(thread cleanup function)。它通常与 pthread_cleanup_pop 一起使用,用于在线程退出时执行一些清理工作。这些清理工作通常包括释放分配的资源或执行必要的操作,以确保线程退出时不会留下未完成的工作或资源泄漏。

下面是 pthread_cleanup_push 的基本用法:

c 复制代码
#include <pthread.h>

void pthread_cleanup_push(void (*routine)(void *), void *arg);
  • routine: 一个函数指针,指向要执行的清理函数。这个函数接受一个 void* 类型的参数,通常用于传递需要清理的资源或数据。

  • arg: 一个 void* 类型的参数,用于传递给清理函数,以便它在执行时能够访问到需要清理的资源或数据。

pthread_cleanup_push 宏的工作方式如下:

  1. 当线程执行到 pthread_cleanup_push 时,会将 routinearg 保存到一个线程本地的清理函数堆栈中。这表示在线程退出时,将按照相反的顺序执行清理函数。

  2. 当线程遇到线程退出点(如调用 pthread_exit、返回从线程函数中等等)时,系统会自动执行清理函数堆栈中的清理函数。清理函数会以相反的顺序执行,即最后一个压入堆栈的函数会最先执行。

下面是一个简单的示例,演示了如何使用 pthread_cleanup_pushpthread_cleanup_pop 来设置线程清理函数:

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

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

void *thread_function(void *arg) {
    pthread_cleanup_push(cleanup_function, "Resource 1");
    pthread_cleanup_push(cleanup_function, "Resource 2");

    // 模拟线程执行过程中的清理
    if (arg != NULL) {
        printf("Thread function received: %s\n", (char *)arg);
    }

    pthread_cleanup_pop(1); // 弹出一个清理函数,但不执行
    pthread_cleanup_pop(1); // 弹出另一个清理函数,并执行

    return NULL;
}

int main() {
    pthread_t my_thread;

    pthread_create(&my_thread, NULL, thread_function, "Hello from main!");

    // 等待新线程完成
    pthread_join(my_thread, NULL);

    printf("Main thread: New thread has finished.\n");

    return 0;
}

在这个示例中,我们使用 pthread_cleanup_push 来设置两个清理函数,它们用于释放资源。在 thread_function 中,我们模拟了一些线程执行期间的操作,并在函数退出时执行清理函数。清理函数以相反的顺序执行,并打印出相应的清理信息。这有助于确保线程退出时资源得到适当地清理。

相关推荐
Fairy_sevenseven12 分钟前
[1]python爬虫入门,爬取豆瓣电影top250实践
开发语言·爬虫·python
聪明的笨猪猪12 分钟前
Java Spring “IOC + DI”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
ThisIsMirror16 分钟前
CompletableFuture并行任务超时处理模板
java·windows·python
lixinnnn.1 小时前
贪心:火烧赤壁
数据结构·c++·算法
珹洺1 小时前
Java-Spring入门指南(二十一)Thymeleaf 视图解析器
java·开发语言·spring
Predestination王瀞潞1 小时前
类的多态(Num020)
开发语言·c++
Predestination王瀞潞1 小时前
类的继承(Num019)
开发语言·c++
Nuyoah11klay1 小时前
华清远见25072班C++学习假期10.3作业
c++
源码集结号1 小时前
一套智慧工地云平台源码,支持监管端、项目管理端,Java+Spring Cloud +UniApp +MySql技术开发
java·mysql·spring cloud·uni-app·源码·智慧工地·成品系统
EnCi Zheng1 小时前
Spring Security 最简配置完全指南-从入门到精通前后端分离安全配置
java·安全·spring