读写者问题是一类比较特殊的问题。可以允许多个读者同时读,但不允许多个写者或者写者和读者同时操作。所以需要保证读者和写者之间的同步与互斥关系,以及多个写者之间的互斥关系。

读写锁是一种自旋锁:自旋锁是当一个线程没有申请资源成功,不会等待,而是一直在进行循环判断是否锁被释放。


  1 #include
  2 #include
  3 
  4 pthread_rwlock_t rwlock;
  5 
  6 int buf;
  7 void *reader(void *arg)
  8 {
  9     while(1)
 10     {
 11         pthread_rwlock_rdlock(&rwlock);
 12         printf("reader%d is reading...:%d\n",(int)arg,buf);
 13         pthread_rwlock_unlock(&rwlock);
 14         sleep(1);
 15 
 16     }
 17 }
 18 void *writer(void *arg)
 19 {
 20     int i = 0;
 21     while(1)
 22     {
 23         pthread_rwlock_wrlock(&rwlock);
 24         buf = i++;
 25         printf("writer:%d\n",buf);
 26         pthread_rwlock_unlock(&rwlock);
 27         sleep(1);
 28     }
 29 }
 30 
 31 int main()
 32 {
 33     pthread_t tid1,tid2,tid3,tid4;
 34     pthread_create(&tid1,NULL,reader,(void*)1);
 35     pthread_create(&tid3,NULL,reader,(void*)2);
 36     pthread_create(&tid2,NULL,writer,NULL);
 37 
 38     pthread_rwlock_init(&rwlock,NULL);
 39     pthread_join(tid1,NULL);
 40     pthread_join(tid3,NULL);
 41     pthread_join(tid2,NULL);
 42     pthread_rwlock_destroy(&rwlock);
 43     return 0;
 44 }
 
 运行结果
 [fbl@localhost rw_lock]$ ./rwlock 
writer:0
reader2 is reading...:0
reader1 is reading...:0
writer:1
reader2 is reading...:1
reader1 is reading...:1
writer:2
reader2 is reading...:2
reader1 is reading...:2
writer:3
reader2 is reading...:3
reader1 is reading...:3
writer:4
reader2 is reading...:4
reader1 is reading...:4
writer:5
reader2 is reading...:5
reader1 is reading...:5
writer:6
reader2 is reading...:6
reader1 is reading...:6