读写锁有三种状态:读锁、写锁和不锁
其特性为:读共享,写独占,写锁优先级高
// 初始化读写锁
int pthread_rwlock_init ( pthread_rwlock_t * restrict rwlock ,
const pthread_rwlockattr_t * restrict attr ) ;
// 销毁读写锁
int pthread_rwlock_destroy (pthread_rwlock_t * rwlock ) ;
// 加读锁
int pthread_rwlock_rdlock ( pthread_rwlock_t * rwlock ) ;
// 加写锁
int pthread_rwlock_wrlock ( pthread_rwlock_t * rwlock ) ;
// 解锁
int pthread_rwlock_unlock ( pthread_rwlock_t * rwlock ) ;
// 尝试加读锁
int pthread_rwlock_tryrdlock ( pthread_rwlock_t * rwlock ) ;
// 尝试加写锁
int pthread_rwlock_trywrlock ( pthread_rwlock_t * rwlock ) ;
下面通过读写锁实现读者写者模型,有3个写者,5个读者:
1 #include<stdio.h>
2 #include<unistd.h>
3 #include<pthread.h>
4 int cont;
5 pthread_rwlock_t rwlock;
6 void *th_write(void *arg)
7 {
8 int t;
9 long int i = (long int)arg;
10
11 while(1)
12 {
13 usleep(1000);
14
15 pthread_rwlock_wrlock(&rwlock);//加写锁
16 t = cont;
17 printf("=====write %ld: %lu: cont = %d, ++cont = %d\n",i,pthread_self(), t, ++cont);
18 pthread_rwlock_unlock(&rwlock);//解锁
19
20 usleep(1000);
21 }
22 }
23 void *th_read(void *arg)
24 {
25 long int i = (long int)arg;
26
27 while(1)
28 {
29 pthread_rwlock_rdlock(&rwlock);//加读锁
30 printf("=======================read %ld: %lu: cont = %d\n",i,pthread_self(),cont);
31 pthread_rwlock_unlock(&rwlock);//解锁
32 usleep(900);
33 }
34 }
35 int main(void)
36 {
37 long int i;
38 pthread_t tid[8];
39
40 pthread_rwlock_init(&rwlock,NULL);//初始化锁
41 for(i = 0;i < 3;i++)
42 {
43 pthread_create(&tid[i],NULL,th_write,(void*)i);
44 }
45 for(i = 0;i < 5;i++)
46 {
47 pthread_create(&tid[i+3],NULL,th_read,(void*)i);
48 }
49 for(int i=0;i < 8;i++)
50 {
51 pthread_join(tid[i],NULL);
52 }
53 pthread_rwlock_destroy(&rwlock);//释放锁
54 }
截取部分运行结果: