linux c线程通讯pthread_cleanup_push()和pthread_cleanup_pop()

  •  概要

                在线程正常或非正常退出时都需要清理线程所占用的资源,pthread_cleanup_push 和 pthread_cleanup_pop函数在线程退出时可以执行指定清理函数

                pthread_cleanup_pop(0),当调用了pthread_cancel() 函数或pthread_exit()时执行指定清理函数。一般pthread_cleanup_pop函数只有参数大于0才会执行指定清理函数

名称pthread_cleanup_push / pthread_cleanup_pop
功能线程清理函数入栈 / 线程清理函数出栈
头文件#include<pthread.h>
原型

pthread_cleanup_push(void (*rnt)(void *), void *arg)

pthread_cleanup_pop(int execute) 

参数

*rnt :     需要执行线程清理函数入口

execute :    执行标示    0    不执行; 1    执行

返回

    

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

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

void *child_one(void *arg)
{
	printf("thread one start\n");
	pthread_cleanup_push(cleanup, "thread one cleapup first\n");
	pthread_cleanup_push(cleanup, "thread one cleanup second\n");
	printf("thread one push complete\n");
	if(arg)
	{
		return ((void*)1);
	}
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);
	return ((void*)1);
}

void child_two(void *arg)
{
	printf("thread two start\n");
	pthread_cleanup_push(cleanup, "thread two cleanup first\n");
	pthread_cleanup_push(cleanup, "thread two cleanup second\n");
	printf("thread two push complete\n");
	if(arg)
	{
		pthread_exit((void*)2);
	}
	pthread_cleanup_pop(cleanup, "thread two cleanup first\n");
	pthread_cleanup_pop(cleanup, "thread two cleanup second\n");
	pthread_exit((void*)2);
}

void main()
{
	pthread_t child1, child2;
	void *tret;
	
	pthread_create(&child1, NULL, child_one, NULL);
	pthread_create(&child2, NULL, child_two, NULL);
	pthread_join(child1, &tret);
	pthread_join(child2, &tret);
}

执行结果:


执行结果中没有调用child_one函数中的pthread_cleanup_push方法中设定的线程清理函数,因为在child_one函数中pthread_cleanup_pop方法中参数为0,并且又没有调用pthread_cancel 和 pthread_exit方法


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值