Chinaunix

标题: {解决}读写锁,写锁呗读锁阻塞了 [打印本页]

作者: o_unix    时间: 2013-02-20 17:13
标题: {解决}读写锁,写锁呗读锁阻塞了
本帖最后由 o_unix 于 2013-02-21 15:59 编辑

大家好,我想测试读写锁,写线程一直不能获得锁,而是读线程一直占据着,代码如下:

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

  5. #define size 10
  6. int i = 0;
  7. pthread_rwlock_t rwlock;

  8. void *read_func( void *arg);
  9. void *write_func( void *arg);

  10. int main( void)
  11. {
  12. int j = 2*size;
  13. pthread_t *tids = (pthread_t *)malloc( j*sizeof( pthread_t));
  14. pthread_rwlockattr_t rwlockattr;
  15. pthread_rwlockattr_init( &rwlockattr);
  16. pthread_rwlockattr_setkind_np (&rwlockattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
  17. pthread_rwlock_init( &rwlock, NULL);
  18. int m = 0;

  19. for( m =0; m < j; m++)
  20. {
  21. if( m < size)
  22. {
  23. pthread_create( tids+m, NULL, write_func, (void*)m);
  24. }
  25. else
  26. {
  27. pthread_create( tids+m, NULL, read_func, (void *)m);
  28. }
  29. }


  30. for( m = 0; m < j; m++)
  31. {
  32. pthread_join( *(tids+m), (void *)0);
  33. }
  34. pthread_rwlock_destroy( &rwlock);
  35. return 0;
  36. }

  37. void * read_func( void *arg)
  38. {
  39. while( i < 10)
  40. {
  41. pthread_rwlock_rdlock( &rwlock);
  42. printf("%d reading i:%d\n", (int)arg, i);
  43. pthread_rwlock_unlock( &rwlock);
  44. }
  45. void *write_func( void *arg)
  46. {
  47. pthread_rwlock_wrlock( &rwlock);
  48. printf("%d read i: %d\n", (int)arg, i++);
  49. printf("%d writing i: %d\n", (int)arg, i);
  50. pthread_rwlock_unlock( &rwlock);
  51. }
  52.                                        
复制代码
我查看锁的状态的发现:
(gdb) print rwlock
$13 = {__data = {__lock = 0, __nr_readers = 10,
    __readers_wakeup = 0, __writer_wakeup = 0,
    __nr_readers_queued = 0, __nr_writers_queued = 10,
    __writer = 0, __pad1 = 0, __pad2 = 0, __pad3 = 0,
    __flags = 0},
  __size = "\000\000\000\000\n", '\0' <repeats 15 times>, "\n", '\0' <repeats 34 times>, __align = 42949672960}

写线程已经在排队了,为什么写线程不能获得锁呢?写锁的优先级不是比读锁高吗?
测试过程中读锁可以抢占写锁,没有出现写锁抢占读锁的情况,请大家给看看我那里理解所了,谢谢先。
作者: o_unix    时间: 2013-02-21 10:38
果然默认是读优先的。现在是写优先的了




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2