mutex互斥量小例程

1400阅读 0评论2014-10-15 vibe26
分类:C/C++

例如int *a  int *b  分别指向两块内存,上面的值分别初始化为(200, 100) 线程A执行这样的一个操作:将*a的值减少50,*b的值增加50.

 线程B执行:打印出(a 跟 b 指向的内存的值的和)。

      如果串行运行:A: *a -= 50; *b += 50;  B: printf("%d\n", *a + *b);  

      如果并发执行,则有可能会出现一下调度:*a -= 50; printf("%d\n", *a + *b); *b += 50;

      因此我们可以引入互斥量,在对共享数据读写时进行锁操作,实现对内存的访问以互斥的形式进行。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <pthread.h>
  4. #include<stdlib.h>
  5.  
  6. int a = 200;
  7. int b = 100;
  8. pthread_mutex_t lock;
  9.  
  10. void* ThreadA(void*argc)
  11. {
  12.     printf("pthreadA is running\n");
  13.     pthread_mutex_lock(&lock); //
  14.     printf("pthreadA locked...\n");
  15.     a -= 50;
  16.     sleep(5); //执行到一半 使用sleep 放弃cpu调度
  17.     b += 50;
  18.     pthread_mutex_unlock(&lock);
  19.     printf("pthreadA unlocked...\n");
  20.     printf("pthreadA exit\n");
  21. }
  22.  
  23. void* ThreadB(void*argc)
  24. {
  25.     sleep(1); //放弃CPU调度 目的先让A线程运行。
  26.     printf("pthreadB is running\n");
  27.     //pthread_mutex_unlock(&lock);
  28.     //printf("pthreadB unlocked...\n");
  29.     pthread_mutex_lock(&lock);
  30.     printf("pthreadB locked...\n");
  31.     printf("%d\n", a + b);
  32.     pthread_mutex_unlock(&lock);
  33.     printf("pthreadB unlocked...\n");
  34.     printf("pthreadB exit\n");
  35. }
  36.  
  37. int main()
  38. {
  39.     pthread_t tida, tidb;
  40.     pthread_mutex_init(&lock, NULL);
  41.     pthread_create(&tida, NULL, ThreadA, NULL);
  42.     pthread_create(&tidb, NULL, ThreadB, NULL);
  43.     pthread_join(tida, NULL);
  44.     pthread_join(tidb, NULL);
  45.     exit(0);
  46. }

运行结果:
[vibe@localhost code]$ ./a
pthreadA is running
pthreadA locked...
pthreadB is running
pthreadA unlocked...
pthreadA exit
pthreadB locked...
300
pthreadB unlocked...
pthreadB exit

上一篇:关于pthread_cleanup_push()与pthread_cleanup_pop()的问题
下一篇:读写锁小例程