LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 642|回复: 0

apue 11-4中pthread_cleanup_push函数是如何清理的?

[复制链接]
发表于 2010-6-20 21:03:49 | 显示全部楼层 |阅读模式
我在运行apue11-4的程序中运行通了,但是对函数不大理解,程序清单如下:
#include "apue.h"
#include <pthread.h>
void cleanup(void *arg)
{
printf("cleanup:%s\n",(char *)arg);
}
void thr_fn1(void *arg)
{
printf("thread 1 start\n");
pthread_cleanup_push(cleanup,"thread 1 first handler");
pthread_cleanup_push(cleanup,"thread 1 second handler");
printf("thread 1 push complete\n");
if(arg)
return ((void *)1);
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return ((void *)1);
}
void * thr_fn2(void *arg)
{
printf("thread 2 start\n");
pthread_cleanup_push(cleanup,"thread 2 first handler");
pthread_cleanup_push(cleanup,"thread 2 second handler");
printf("thread 2 push complete\n");
if(arg)
return ((void *)2);
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
int main(void)
{
int err;
pthread_t tid1,tid2;
void *tret;
err=pthread_create(&tid1,NULL,thr_fn1,(void *)1);
if(err!=0)
err_quit("can't create thread 1:%s\n",strerror(err));
err=pthread_create(&tid2,NULL,thr_fn2,(void *)1);
if(err!=0)
err_quit("can't create thread 2:%s\n",strerror(err));
err=pthread_join(tid1,&tret);
if(err!=0)
err_quit("can't join with thread 1:%s\n",strerror(err));
printf("thread 1 exit code %d\n",(int )tret);
err=pthread_join(tid2,&tret);
if(err!=0)
err_quit("can't join with thread 2:%s\n",strerror(err));
printf("thread 2 exit code %d\n",(int )tret);
exit(0);
}
运行结果是
./a.out
thread 1 start
thread 1 push complete
thread 2 start
thread 2 push complete
cleanup:thread 2 second handler
cleanup: thread 2 first handler
thread 1 exit code 23
thread 2 exit code 2
问题是pthread_cleanup_push函数当调用cleanup函数时,打印提示说在处理线程1的处理,而cleanup函数就是一句printf("cleanup:%s\n",(char *)arg);语句,他是如何处理线程的?难道打印说处理在内存上就处理了吗?还有就是为什么运行结果没有打印cleanup:thread 1 second handler
cleanup: thread 1 first handler   
而且先打印thread 2 second handler 而不是thread 2 firs thandler?
新手入门,问的也只能这么肤浅,望高手指点
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表