Chinaunix首页 | 论坛 | 博客
  • 博客访问: 78704
  • 博文数量: 8
  • 博客积分: 228
  • 博客等级: 二等列兵
  • 技术积分: 153
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-04 22:00
文章分类
文章存档

2012年(8)

分类: LINUX

2012-10-11 16:14:24

读写锁与互斥量相似,不过读写锁允许更高的并行性。互斥量要么是锁住状态,要不是不加锁状态,
而且一次只有一个线程可以对其进行加锁。读写锁有三种状态:读模式加锁,写模式加锁,不加锁。
1.当读写锁是写加锁时,在这个锁被解索之前所有企图对它加锁的线程都将要阻塞。
2.当读写锁是读加锁时,在这个锁被解索之前所有企图以读模式对它加锁的线程都可以获得访问权;以写模式
加锁的线程将堵塞,并且堵塞随后的读模式加锁。这样可以避免读模式锁长期占用,导致等待的写模式锁请求
一直得不到满足。

点击(此处)折叠或打开

  1. #include
  2. #include
  3. #include
  4. struct my_file
  5. {
  6. int num;
  7. pthread_rwlock_t lock_num;
  8. };

  9. void * write1(void *arg)
  10. {
  11. struct my_file *file_info=(struct my_file *)arg;
  12. pthread_rwlock_wrlock(&file_info->lock_num);
  13. printf("write1:my_file->num:%d,process=%d,thread num:%d\n",file_info->num++,getpid(),pthread_self());
  14. pthread_rwlock_unlock(&file_info->lock_num);
  15. return((void *)1);
  16. }

  17. void *write2(void *arg)
  18. {
  19. struct my_file *file_info=(struct my_file *)arg;
  20. pthread_rwlock_wrlock(&file_info->lock_num);
  21. printf("write2:my_file->num:%d,process=%d,thread num:%d\n",file_info->num++,getpid(),pthread_self());
  22. sleep(3);
  23. pthread_rwlock_unlock(&file_info->lock_num);

  24. return((void *)2);
  25. }

  26. void *read(void *arg)
  27. {

  28. struct my_file *file_info=(struct my_file *)arg;
  29. printf("enter read:\n");
  30. pthread_rwlock_rdlock(&file_info->lock_num);
  31. printf("read:my_file->lock_num:%d,process=%d,thread num:%d\n",file_info->num,getpid(),pthread_self());
  32. pthread_rwlock_unlock(&file_info->lock_num);
  33. printf("after read:\n");
  34. return((void *)3);
  35. }

  36. int main(void)
  37. {
  38. pthread_t th1,th2,th3;
  39. struct my_file *test;
  40. test= (struct my_file *)malloc(sizeof(struct my_file )*1);
  41. if( test == NULL )
  42. {
  43. perror("allocate is failed");
  44. return 0;
  45. }
  46. test->num=0;
  47. pthread_rwlock_init(&test->lock_num,NULL);

  48. int ret;
  49. while(test->num<10)
  50. {
  51. ret==pthread_create(&th1,NULL,write1,test);
  52. if( ret != 0 )
  53. {
  54. perror("pthread1 error");
  55. return 0;
  56. }
  57. usleep(1000);
  58. pthread_create(&th2,NULL,write2,test);
  59. if( ret != 0 )
  60. {
  61. perror("pthread2 error");
  62. return 0;
  63. }
  64. usleep(1000);
  65. pthread_create(&th3,NULL,read,test);
  66. if( ret != 0 )
  67. {
  68. perror("pthread3 error");
  69. return 0;
  70. }
  71. pthread_join(th3,NULL);
  72. pthread_rwlock_destroy(&test->lock_num);
  73. }
  74. free(test);
  75. test=NULL;
  76. return 1;

阅读(12727) | 评论(1) | 转发(3) |
给主人留下些什么吧!~~

xql2004xp2016-05-13 13:15:17

glibc实现的读写锁,无论使用读者优先还是写者优先选项,都会在有大量写操作的时候出现无法读取的问题。
http://blog.jerrylab.info/2016/05/duiposixduxiesuomokuaidefenxi 这篇文章中分析了这个问题,不知道对不对,请教一下。