Linux多线程C++版(四) 线程清理和控制 pthread_cleanup_push()函数 pthread_cleanup_pop()函数 线程和进程的启动和终止比较

16 篇文章 2 订阅
9 篇文章 3 订阅

1.线程清理和控制
#include<pthread.h>
void pthread_cleanup_push(void (*rtn)(void*),void* arg);
void pthread_cleanup_pop(int execute);
返回:成功返回0,否则返回错误编号
这个是一组是成对出现的
  • 参数
    • rtn:用户定义的清理函数指针
    • arg:调用清理函数传递的参数
    • execute:值1时执行线程清理函数,值为0不执行线程清理函数
  • 触发线程调用清理函数的动作 有三种情况
    • 调用pthread_exit
    • 响应取消请求— 进程中的其他线程调用pthread_cancel此线程被取消了
    • 用非零execute参数调用pthread_cleanup_pop时
#include<pthread.h>
#include<stdlib.h>
#include<stdio.h>

//定义线程清理函数
void clean_fun(void *arg){
    char *s = (char*)arg;
    printf("clean_func: %s\n",s);
}

//定义线程执行函数
void* th_fun(void *arg){
    int execute = (int)arg;
    pthread_cleanup_push(clean_fun,"first clean func");
    pthread_cleanup_push(clean_fun,"second clean func");
    printf("threadd running %ls\n",pthread_self());
    pthread_cleanup_pop(execute);
    pthread_cleanup_pop(execute);
    return (void*)0;
}

int main(void){
    int err;
    pthread_t th1,th2;
    if((err = pthread_create(&th1,null,th_fun,(void*)1)!=0){
        printf("pthread create error");
    }
    pthread_join(th1,null);
    printf("th1(%lx) finished\n",th1);
       
    if((err = pthread_create(&th2,null,th_fun,(void*)1)!=0){
        printf("pthread create error");
    }
    pthread_join(th2,null);
    printf("th2(%lx) finished\n",th2);
}

代码运行结果

在这里插入图片描述

id((err = pthread_create(&th1,null,th_fun,(void*)0)!=0){
        printf("pthread create error");
    }//当传入参数是0是 不调用线程清理函数
/*
	此时th1线程只运行了printf("threadd running %ls\n",pthread_self());和printf("th1(%lx) finished\n",th1);两个输出语句,没有运行线程清理函数中的输出语句,th2线程运行了线程清理函数
	和
*/

在这里插入图片描述

2.线程和进程的 启动和终止的 比较
进程线程
fork()pthread_create()
return/exit()/_exit()return/pthread_exit()
wait()pthread_join()
atexit()pthread_clean_push/pthread_clean_pop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unknown To Known

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值