线程退出处理函数 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;
}


你可能感兴趣的:(线程退出处理函数 pthread_cleanup_push pthread_cleanup_pop)