免费注册 查看新帖 |

Chinaunix

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

线程私有数据 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-03-12 15:04 |只看该作者 |倒序浏览
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. pthread_key_t   key;

  4. void echomsg(int  t)
  5. {
  6.    printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);   
  7.        
  8. }
  9. void * child1(void *arg)
  10. {
  11.        int tid=pthread_self();
  12.        printf("thread %d enter\n",tid);
  13.       pthread_setspecific(key,(void *)tid);
  14.       sleep(2);
  15.       printf("thread %d returns %d\n",tid,pthread_getspecific(key));
  16.      sleep(5);
  17. }
  18.        
  19. void * child2(void *arg)
  20. {
  21.      int tid=pthread_self();
  22.      printf("thread %d enter\n",tid);
  23.      pthread_setspecific(key,(void *)tid);
  24.      sleep(1);
  25.      printf("thread %d returns %d\n",tid,pthread_getspecific(key));
  26.      sleep(5);
  27. }

  28. int main(void)
  29. {
  30.     int tid1,tid2;
  31.     printf("hello\n");
  32.     pthread_key_create(&key,echomsg);
  33.     pthread_create(&tid1,NULL,child1,NULL);
  34.     pthread_create(&tid2,NULL,child2,NULL);
  35.     sleep(10);
  36.     pthread_key_delete(key);
  37.     printf("main thread exit\n");
  38.     return 0;
  39. }
复制代码

该代码执行结果并没有执行echomsg函数,在书上也谈到上述程序说是程序错开了两个线程私有数据的写入和读出时间,实在不明白这是什么原因,为什么没执行echomsg函数?谢谢!!!

论坛徽章:
0
2 [报告]
发表于 2007-03-12 16:14 |只看该作者
大家帮帮忙看一下,再次谢过!

论坛徽章:
0
3 [报告]
发表于 2007-03-12 16:43 |只看该作者
你在什么环境下编译的,我咋试的没问题呢?

hello
thread 134558720 enter
thread 134559232 enter
thread 134559232 returns 134559232
thread 134558720 returns 134558720
destructor excuted in thread 134559232,param=134559232
destructor excuted in thread 134558720,param=134558720
main thread exit

论坛徽章:
0
4 [报告]
发表于 2007-03-12 16:56 |只看该作者
redhat 9
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP