关于posix线程清理 pthread_cleanup

docici 发布于 2015/11/27 13:13
阅读 176
收藏 0

开源之夏第三届火热来袭,高校学生参与赢万元奖金!>>>

/*!
 * 测试pthread_cleanup push/pop,
 * 源于APUE3(UNIX环境高级编程第3版 W. Richard Stevens, Stephen A. Rago蓍 )
 * 很奇怪, 改了文件后缀名后运行输出结果不一样
 * .cpp的输出结果:
thread 2 start!!!
cleanup: thread2
cleanup: thread2
thread 1 start!!!
cleanup: thread1
cleanup: thread1
thread 1 exit code 1
thread 1 exit code 2
 *
 * .c的输出结果:
thread 2 start!!!
cleanup: thread2
cleanup: thread2
thread 1 start!!!
thread 1 exit code 1
thread 1 exit code 2
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void cleanup(void * msg){
	printf("cleanup: %s\n", msg? (char *)msg : "(NULL)");
}
void * thread_fn1(void * arg){
	printf("thread 1 start!!!\n");
	pthread_cleanup_push(cleanup, (void *)"thread1");
	pthread_cleanup_push(cleanup, (void *)"thread1");
	if(arg){
		return ((void *)1);	//不同之处
	}
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);
	return (void *)1;
}
void * thread_fn2(void * arg){
	printf("thread 2 start!!!\n");
	pthread_cleanup_push(cleanup, (void *)"thread2");
	pthread_cleanup_push(cleanup, (void *)"thread2");
	if(arg){
		pthread_exit((void *)2);	//不同之处
	}
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);
	pthread_exit((void *)2);	//不同之处

}

int main(int argc, char * argv[]){
	pthread_t tid1, tid2;
	void * tret = 0;
	int ret = pthread_create(&tid1, NULL, thread_fn1, (void *)1);
	if(ret != 0){
		printf("pthread_create failed!\n");
		return -1;
	}
	ret = pthread_create(&tid2, NULL, thread_fn2, (void *)1);
	if(ret != 0) {
		printf("pthread_create failed!\n");
		return -1;
	}

	pthread_join(tid1, &tret);
	printf("thread 1 exit code %ld\n", (long)tret);
	pthread_join(tid2, &tret);
	printf("thread 1 exit code %ld\n", (long)tret);


	exit (0);
}



加载中
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部
返回顶部
顶部