免费注册 查看新帖 |

Chinaunix

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

互斥锁 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-23 19:46 |只看该作者 |倒序浏览
  1 #include
  2 #include
  3 int a = 0;
  4
  5 pthread_mutex_t number;
  6 void * th_1(void *arg)
  7 {
  8  pthread_mutex_lock(&number);
  9  a = a + 1;
10  printf("%d\n",a);
11  sleep(3);
12  a = a + 1;
13  printf("%d\n",a);
14  pthread_mutex_unlock(&number);
15 }
16 void * th_2(void*arg)
17 {
18 pthread_mutex_lock(&number);
19 printf("wait for th_2:\n");
20 printf("%d\n",a);
21 a = a + 1;
22 printf("%d\n",a);
23 pthread_mutex_unlock(&number);
24 }
25 int main(void)
26 {
27
28 pthread_t th1;
29 pthread_t th2;
30 pthread_create(&th1,NULL,(void*)th_1,NULL);
31 pthread_create(&th2,NULL,(void*)th_2,NULL);
32 sleep(4);
33
34 }
  th_1和th_2分别对全局变量a进行改变,加了互斥锁之后,th_1不受th_2的干扰,th_2被阻塞一直到th_1解锁后,之后才能对a进行修改。而且th_2被阻塞在上锁此刻,之前的语句不会被阻塞 。      
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/108685/showart_2129155.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP