讀寫者問題------讀寫鎖


讀寫者問題是一類比較特殊的問題。可以允許多個讀者同時讀,但不允許多個寫者或者寫者和讀者同時操作。所以需要保證讀者和寫者之間的同步與互斥關係,以及多個寫者之間的互斥關係。

讀寫鎖是一種自旋鎖:自旋鎖是當一個線程沒有申請資源成功,不會等待,而是一直在進行循環判斷是否鎖被釋放。


  1 #include<stdio.h>
  2 #include<pthread.h>
  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






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章