Chinaunix首页 | 论坛 | 博客
  • 博客访问: 61156
  • 博文数量: 96
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 852
  • 用 户 组: 普通用户
  • 注册时间: 2014-07-13 20:47
个人简介

扎斯特都恩特

文章分类

全部博文(96)

文章存档

2018年(1)

2017年(2)

2016年(82)

2015年(11)

我的朋友

分类: LINUX

2015-10-18 19:04:30


点击(此处)折叠或打开

  1. #include "stdio.h"
  2. #include "string.h"
  3. #include "pthread.h"
  4. #include "unistd.h"

  5. int counter;
  6. pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;/*定义并初始化互斥锁*/

  7. void *update(void *vptr)
  8. {
  9.     int i,val;
  10.     
  11.     while(1)
  12.     {
  13.      pthread_mutex_lock(&counter_mutex);/*上锁*/
  14.         val = counter;
  15.         printf("%x: %d\n",(unsigned int)pthread_self(),val+1);
  16.         counter = val + 1;
  17.         pthread_mutex_unlock(&counter_mutex);/*开锁*/
  18.         sleep(1);
  19.     }
  20.     
  21.     return NULL;
  22. }

  23. int main(int argc, char *argv[])
  24. {
  25.     pthread_t tha,thb;
  26.     
  27.     pthread_create(&tha,NULL,&update,NULL);/*创建两个线程,调用同一个函数*/
  28.     pthread_create(&thb,NULL,&update,NULL);
  29.     
  30.     pthread_join(tha,NULL);
  31.     pthread_join(thb,NULL);

  32.     return 0;    
  33. }
编      译:gcc -o mutex  pthread_mutex.c -l pthread
运行结果:
b7f42b90: 1
b7541b90: 2
b7f42b90: 3
b7541b90: 4
b7f42b90: 5
b7541b90: 6
b7f42b90: 7
b7541b90: 8




Tips:
可以将lock和unlock两句注释掉,对比看下运行结果--

阅读(606) | 评论(0) | 转发(0) |
0

上一篇:pthread_cancel

下一篇:gdb(一)

给主人留下些什么吧!~~