免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1144 | 回复: 0
打印 上一主题 下一主题

[C++] pthread_cleanup_push与pthread_cleanup_pop [复制链接]

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:58:11
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-11-25 08:48 |只看该作者 |倒序浏览
apue p295的代码,讲解pthread_cleanup_push和pthread_cleanup_pop的使用,有个地方不太明白,求解释一下。

代码:
  1. #include <stdio.h>
  2. #include <pthread.h>

  3. void cleanup(void *arg)
  4. {
  5.     printf("cleanup : %s \n", (char*)arg);
  6. }

  7. void *thr_fn1(void *arg)
  8. {
  9.     printf("thread 1 start \n");
  10.     pthread_cleanup_push(cleanup, const_cast<char*>("thread 1 first handler"));
  11.     pthread_cleanup_push(cleanup, const_cast<char*>("thread 1 second handler"));
  12.     printf("thread 1 push complete\n");

  13.     if (arg)
  14.     {
  15.         return ((void*)1);
  16.     }
  17.     pthread_cleanup_pop(0);
  18.     pthread_cleanup_pop(0);
  19.     return ((void*)1);
  20. }

  21. void *thr_fn2(void *arg)
  22. {
  23.     printf("thread 2 start\n");
  24.     pthread_cleanup_push(cleanup, const_cast<char*>("thread 2 first handler"));
  25.     pthread_cleanup_push(cleanup, const_cast<char*>("thread 2 second handler"));
  26.     printf("thread 2 push complete\n");
  27.     if (arg)
  28.     {
  29.         pthread_exit((void*)2);
  30.     }
  31.     pthread_cleanup_pop(0);
  32.     pthread_cleanup_pop(0);
  33.     pthread_exit((void*)2);
  34. }

  35. int main(int argc, char **argv)
  36. {
  37.     pthread_t tid1, tid2;
  38.     void *tret;

  39.     pthread_create(&tid1, NULL, thr_fn1, (void*)1);
  40.     pthread_create(&tid2, NULL, thr_fn2, (void*)1);

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

  43.     pthread_join(tid2, &tret);
  44.     printf("thread 2 exit code %ld\n", (long)tret);

  45.     return 0;
  46. }
复制代码
有些不太明白的地方是:
1、书上说了,如果以0调用pthread_cleanup_push,则清理函数不会被调用,且不论以什么方式调用,pthread_cleanup_pop都会删除上次pthread_cleanup_push调用建立的清理函数。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP