免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2581 | 回复: 1

[C] 使用 pthread_mutex_lock thread 交错 [复制链接]

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:49:03
发表于 2016-05-12 00:12 |显示全部楼层
本帖最后由 shihyu 于 2016-05-12 00:12 编辑
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>

  4. static pthread_mutex_t Cmtx = PTHREAD_MUTEX_INITIALIZER;

  5. void* ap1_thread(void* args)
  6. {
  7.     while (1) {
  8.         pthread_mutex_lock(&Cmtx);
  9.         printf("ap1_thread[+]\n");
  10.         pthread_mutex_unlock(&Cmtx);
  11.         sleep(1);
  12.     }

  13.     return NULL;
  14. }

  15. void* ap2_thread(void* args)
  16. {
  17.     while (1) {
  18.         pthread_mutex_lock(&Cmtx);
  19.         printf("ap2_thread[-]\n");
  20.         pthread_mutex_unlock(&Cmtx);
  21.         sleep(1);
  22.     }

  23.     return NULL;
  24. }

  25. int main(int argc, char* argv[])
  26. {
  27.     pthread_t thread1, thread2;

  28.     pthread_create(&thread1, NULL, ap1_thread, NULL);
  29.     pthread_create(&thread2, NULL, ap2_thread, NULL);

  30.     pthread_join(thread1, NULL);
  31.     pthread_join(thread2, NULL);

  32.     return 0;
  33. }
复制代码
我起两个 thread 测试交错打印

pthread_mutex_unlock 之后过故意sleep(1) 让另一条thread 可以先lock
这样应该是
ap1_thread[+]
ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
不断交错

, 可是我测试结果会出现有连续印两个ap2_thread[-]

ap1_thread[+]
ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
ap2_thread[-]
ap1_thread[+]
ap2_thread[-]
ap1_thread[+]

请问这是可能是什么原因造成

谢谢

论坛徽章:
44
15-16赛季CBA联赛之浙江
日期:2021-10-11 02:03:59程序设计版块每日发帖之星
日期:2016-07-02 06:20:0015-16赛季CBA联赛之新疆
日期:2016-04-25 10:55:452016科比退役纪念章
日期:2016-04-23 00:51:2315-16赛季CBA联赛之山东
日期:2016-04-17 12:00:2815-16赛季CBA联赛之福建
日期:2016-04-12 15:21:2915-16赛季CBA联赛之辽宁
日期:2016-03-24 21:38:2715-16赛季CBA联赛之福建
日期:2016-03-18 12:13:4015-16赛季CBA联赛之佛山
日期:2016-02-05 00:55:2015-16赛季CBA联赛之佛山
日期:2016-02-04 21:11:3615-16赛季CBA联赛之天津
日期:2016-11-02 00:33:1215-16赛季CBA联赛之浙江
日期:2017-01-13 01:31:49
发表于 2016-05-12 01:03 |显示全部楼层
本帖最后由 windoze 于 2016-05-12 01:04 编辑

你的代码没有让两个thread“交错”,只是让两个thread不要一起执行lock中间的那行代码而已。

不要假设OS调度线程的方式,它完全可以让一个thread先跑完再跑另一个,完全符合你的代码写出来的行为。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP