特点:与互斥锁类似,但读写锁允许更高的并行性。(写时独占,读时共享,写锁优先级高)
读写锁状态:
- 读模式下加锁
- 写模式下加锁
- 不加锁
1 /*头文件:#include<pthread.h>
2
3 初始化读写锁:
4 动态初始化:
5 int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
6 静态初始化:
7 pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
8
9 销毁锁:
10 int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
11
12 加读锁:
13 int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
14
15 尝试加读锁:
16 int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
17
18 加写锁:
19 int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
20
21 尝试加写锁
22 int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
23
24 解锁:
25 int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
26
27 pthread_rwlock_t rwlock:定义rwlock为读写锁
28 */
29
30 #include<stdio.h>
31 #include<pthread.h>
32 #include<unistd.h>
33 #include<stdlib.h>
34 //定义全局变量:锁
35 pthread_rwlock_t rwlock;
36
37 int count=500;
38 void *th1(void *)
39 {
40 while(1){
41 //加锁
42 pthread_rwlock_rdlock(&rwlock);
43 printf("read_____%d\n",count);
44 pthread_rwlock_unlock(&rwlock);
45 sleep(0);
46 }
47 }
48 void *th2(void *)
49 {
50 while(1){
51 //加锁
52 int i;
53 i=pthread_rwlock_wrlock(&rwlock);
54 printf("write____%d\n",++count);
55 pthread_rwlock_unlock(&rwlock);
56 if(i!=0){printf("sdfsf\n");}
57 sleep(0);
58 }
59
60 }
61 void main(void)
62 {
63 //创建两个线程
64 pthread_t TH1,TH2;
65 pthread_create(&TH1,NULL,th1,NULL);
66 pthread_create(&TH2,NULL,th2,NULL);
67 //初始化互斥锁
68 pthread_rwlock_init(&rwlock,NULL);
69
70 while(1);
71 //回收线程
72 pthread_join(TH1,NULL);
73 pthread_join(TH2,NULL);
74 }