线程退出处理函数 pthread_cleanup_push pthread_cleanup_pop



/*
 * cleanup.c
 *
 *  Created on: 2011-11-22
 *      Author: lc
 */

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>

/*
 * pthread_cleanup_push
 * pthread_cleanup_pop函数
 * 为线程退出提供处理程序(函数)
 *
 * 函数cleanup会在以下3种情况下被调用
 * 1.线程调用pthread_exit函数
 * 2.线程相应pthread_cancel函数
 * 3.pthread_cleanup_pop函数的参数是非0值
 *
 *
 *  注意 pthread_cleanup_push 要和pthread_cleanup_pop函数配对使用,
 *  否则程序可能编译通不过(expected declaration or statement at end of input)
 */
void cleanup(void * arg) {
	fprintf(stderr, "%s thread cleanup handler invoked\n", (char *) arg);
}

void * thread1(void * arg) {
	fprintf(stderr, "thread 1 start\n");
	pthread_cleanup_push(cleanup,(void *)"thread 1 first");
	pthread_cleanup_push(cleanup,(void *)"thread 1 second");

	if(arg) {
		pthread_exit((void *)1);
	}
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);
	pthread_exit((void *)1);
}

void * thread2(void * arg) {
	fprintf(stderr,"thread 2 start\n");
	pthread_cleanup_push(cleanup,(void *)"thread 2 first");
	pthread_cleanup_push(cleanup,(void *)"thread 2 second");

	if(arg) {
		return (void *)2;
	}
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);

	return (void *)2;
}

void * thread3(void * arg) {
	fprintf(stderr,"thread 3 start\n");
	pthread_cleanup_push(cleanup,(void *)"thread 3 first");
	pthread_cleanup_push(cleanup,(void *)"thread 3 second");

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

	return (void *)3;
}

int main(int argc, char **argv) {
	int ret;
	pthread_t tid1,tid2,tid3;
	void *val;

	ret = pthread_create(&tid1,NULL,thread1,(void *)1);
	if(ret !=0) {
		fprintf(stderr,"%s\n",strerror(errno));
	}

	ret = pthread_create(&tid2,NULL,thread2,(void*)2);
	if(ret !=0) {
		fprintf(stderr,"%s\n",strerror(errno));
	}

	ret = pthread_create(&tid3,NULL,thread3,(void *)0);
	if(ret !=0) {
		fprintf(stderr,"%s\n",strerror(errno));
	}

	ret = pthread_join(tid1,&val);

	if(ret != 0) {
		fprintf(stderr,"%s\n",strerror(errno));
	}
	fprintf(stderr,"thread1 exit with code %d\n",(int)val);

	ret = pthread_join(tid2,&val);
	if(ret !=0) {
		fprintf(stderr,"%s\n",strerror(errno));
	}
	fprintf(stderr,"thread2 exit with code %d\n",(int)val);


	ret = pthread_join(tid3,&val);
	if(ret !=0) {
		fprintf(stderr,"%s\n",strerror(errno));
	}

	fprintf(stderr,"thread3 exit with code %d\n",(int)val);

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值