读写锁:与互斥锁(互斥量相似)但性能更高一些;其特性为:写独占,读共享;
读写锁状态:
一把锁具有三种状态:
1.读模式下的锁状态(读锁);
2.写模式下的锁状态(写锁);
3不加锁;
读写锁特点:写独占,读共享,写锁优先级高;
1.读写锁是以“写模式加锁”时,解锁前,所有对该锁加锁的线程都会被阻塞;
2.读写锁是以“读模式加锁”时,如果剩下所有线程都以读模式对其加锁会成功,如果线程中有写模式,则会阻塞,直到第一个访问的线程将锁打开,然后写锁会加锁成功;
3.读写锁是以“读模式”加锁时,既有试图以“写模式”加锁的线程,又有试图以“读模式”加锁的线程,那么读写锁会阻塞随后的读模式锁请求,优先满足“写模式”锁。读锁写锁并行阻塞时,写锁优先级高;
读写锁实例:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <pthread.h>
5 #include <unistd.h>
6
7 int counter;
8 pthread_rwlock_t rwlock;
9
10 void* th_write(void* arg)
11 {
12 int t ;
13 int i = (int)arg;
14 while(1)
15 {
16 t = counter;
17 usleep(1000);
18 pthread_rwlock_wrlock(&rwlock);
19 printf("=================write %d:%lu:counter = %d ++counter = %d\n",i,pthread_self(),t,++counter);
20 pthread_rwlock_unlock(&rwlock);
21 usleep(5000);
22 }
23 return NULL;
24 }
25 void* th_read(void* arg)
26 {
27 int i = (int) arg;
28 while(1)
29 {
30 pthread_rwlock_rdlock(&rwlock);
31 printf("===========================read %d :%lu : %d\n",i,pthread_self(),counter);
32 pthread_rwlock_unlock(&rwlock);
33 usleep(900);
34 }
35 return NULL;
36 }
37
38
39 int main()
40 {
41 pthread_t tid[8];
42 pthread_rwlock_init(&rwlock,NULL);
43 for(int i = 0;i < 3;i++)
44 {
45 pthread_create(&tid[i],NULL,th_write,(void*)i);
46 }
47 for(int i = 0;i < 5;i++)
48 {
49 pthread_create(&tid[i+3],NULL,th_read,(void*)i);
50 }
51 for(int i = 0;i< 8; i++)
52 {
53 pthread_join(tid[i],NULL);
54 }
55 pthread_rwlock_destroy(&rwlock);
56 return 0;
57 }
结论:写锁优先级高于读锁,在一个线程失去cpu后,另外线程中,写锁会最先获取锁;
-- 插入 -- 35,14-21 顶端