免费注册 查看新帖 |

Chinaunix

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

互斥锁的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-12-13 02:05 |只看该作者 |倒序浏览
我在运行《深入理解计算机系统》这本书“并发编程”这一章中的一个互斥锁的例子时,结果不对,请大牛给分析一下。

  1. #include<pthread.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<semaphore.h>

  5. #define NITERS 10000000
  6. void *count(void *arg);
  7. unsigned int cnt=0;

  8. sem_t mutex;

  9. int main()
  10. {

  11. sem_init(&mutex,0,1);
  12. pthread_t tid1,tid2;
  13. pthread_create(&tid1,NULL,count,NULL);
  14. pthread_create(&tid2,NULL,count,NULL);
  15. pthread_join(tid1,NULL);
  16. pthread_join(tid2,NULL);

  17. if(cnt != (unsigned)NITERS*2)
  18.         printf("Boom! cn=%d \n",cnt);
  19. else
  20.         printf("OK cnt=%d \n",cnt);
  21. exit(0);
  22. }
  23. void *count(void*arg)
  24. {

  25. int i;
  26. for(i=0;i<NITERS;i++)
  27. {
  28.         sem_wait(&mutex);
  29.         cnt++;
  30.         sem_post(&mutex);

  31. }
  32. return NULL;
  33. }
复制代码


机器环境是MacOSX 10.4,编译器是gcc 4.0

[ 本帖最后由 wxs1024 于 2005-12-13 02:07 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2005-12-13 09:15 |只看该作者
两个线程都sem_wait了,没有可以sem_post的线程了

论坛徽章:
0
3 [报告]
发表于 2005-12-13 12:34 |只看该作者
不是楼上说的问题,刚才我在linux x86的机器上运行了,结果正确,在macosx
上就是不对,晕了

论坛徽章:
0
4 [报告]
发表于 2005-12-13 13:07 |只看该作者
原帖由 wxs1024 于 2005-12-13 12:34 发表
不是楼上说的问题,刚才我在linux x86的机器上运行了,结果正确,在macosx
上就是不对,晕了


明白了,我原来对信号灯的理解不对,现在我这里试了也是ok的,redhat 9
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP