Chinaunix首页 | 论坛 | 博客
  • 博客访问: 417484
  • 博文数量: 121
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1393
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-11 12:17
个人简介

www.vibexie.com vibexie@qq.com

文章分类

全部博文(121)

文章存档

2015年(55)

2014年(66)

我的朋友

分类: C/C++

2014-10-15 01:50:15


点击(此处)折叠或打开

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

  5. int a = 200;
  6. int b = 100;
  7. pthread_rwlock_t lock;

  8. void* ThreadA(void*argc)
  9. {
  10.     printf("pthreadA is running\n");
  11.     pthread_rwlock_wrlock(&lock); //写锁
  12.     printf("pthreadA write locked...\n");
  13.     a -= 50;
  14.     sleep(5); //执行到一半 使用sleep 放弃cpu调度
  15.     b += 50;
  16.     pthread_rwlock_unlock(&lock);
  17.     printf("pthreadA write unlocked...\n");
  18.     printf("pthreadA exit\n");
  19. }

  20. void* ThreadB(void*argc)
  21. {
  22.     sleep(1); //放弃CPU调度
  23.     printf("pthreadB is running\n");
  24.     pthread_rwlock_rdlock(&lock);
  25.     printf("pthreadB read locked...\n");
  26.     printf("%d\n", a + b);
  27.     sleep(2);//让线程C读
  28.     pthread_rwlock_unlock(&lock);
  29.     printf("pthreadB read unlocked...\n");
  30.     printf("pthreadB exit\n");
  31. }

  32. void* ThreadC(void*argc)
  33. {
  34.     sleep(1); //放弃CPU调度
  35.     printf("pthreadC is running\n");
  36.     pthread_rwlock_rdlock(&lock);
  37.     printf("pthreadC read locked...\n");
  38.     printf("%d\n", a + b);
  39.     pthread_rwlock_unlock(&lock);
  40.     printf("pthreadC read unlocked...\n");
  41.     printf("pthreadC exit\n");
  42. }

  43. int main()
  44. {
  45.     pthread_t tida, tidb,tidc;
  46.     pthread_rwlock_init(&lock, NULL);
  47.     pthread_create(&tida, NULL, ThreadA, NULL);
  48.     pthread_create(&tidb, NULL, ThreadB, NULL);
  49.     pthread_create(&tidc, NULL, ThreadC, NULL);
  50.     pthread_join(tida, NULL);
  51.     pthread_join(tidb, NULL);
  52.     pthread_join(tidc, NULL);
  53.     pthread_rwlock_destroy(&lock);
  54.     exit(0);
  55. }
运行结果如下:
pthreadA is running
pthreadA write locked...
pthreadB is running
pthreadC is running
pthreadA write unlocked...
pthreadA exit
pthreadB read locked...
300
pthreadC read locked...
300
pthreadC read unlocked...
pthreadC exit
pthreadB read unlocked...
pthreadB exit

将代码的第30行注释掉,运行结果如下:
pthreadA is running
pthreadA write locked...
pthreadB is running
pthreadC is running
pthreadA write unlocked...
pthreadA exit
pthreadB read locked...
300
pthreadB read unlocked...
pthreadB exit
pthreadC read locked...
300
pthreadC read unlocked...
pthreadC exit

本文未详细说明,看不懂可以通过左上角联系方式联系我
阅读(1428) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~