1# RwLock读写锁
2:::{note}
3本文作者: sujintao
4
5Email: <sujintao@dragonos.org>
6:::
7
8## 1. 简介
9&emsp;&emsp;读写锁是一种在并发环境下保护多进程间共享数据的机制.  相比于普通的spinlock,读写锁将对
10共享数据的访问分为读和写两种类型: 只读取共享数据的访问使用读锁控制,修改共享数据的访问使用
11写锁控制. 读写锁设计允许同时存在多个"读者"(只读取共享数据的访问)和一个"写者"(修改共享数据
12的访问), 对于一些大部分情况都是读访问的共享数据来说,使用读写锁控制访问可以一定程度上提升性能.
13
14## 2. DragonOS中读写锁的实现
15### 2.1 读写锁的机理
16&emsp;&emsp;读写锁的目的是维护多线程系统中的共享变量的一致性. 数据会被包裹在一个RwLock的数据结构中, 一切的访问必须通过RwLock的数据结构进行访问和修改. 每个要访问共享数据的会获得一个守卫(guard), 只读进程获得READER(读者守卫),需要修改共享变量的进程获得WRITER(写者守卫),作为RwLock的"影子", 线程都根据guard来进行访问和修改操作.
17
18&emsp;&emsp;在实践中, 读写锁除了READER, WRITER, 还增加了UPGRADER; 这是一种介于READER和WRITER之间的守卫, 这个守卫的作用就是防止WRITER的饿死(Staration).当进程获得UPGRADER时,进程把它当成READER来使用;但是UPGRADER可以进行升级处理,升级后的UPGRADER相当于是一个WRITER守卫,可以对共享数据执行写操作.
19
20&emsp;&emsp;所有守卫都满足rust原生的RAII机理,当守卫所在的作用域结束时,守卫将自动释放.
21
22### 2.2 读写锁守卫之间的关系
23&emsp;&emsp;同一时间点, 可以存在多个READER, 即可以同时有多个进程对共享数据进行访问;同一时间只能存在一个WRITER,而且当有一个进程获得WRITER时,不能存在READER和UPGRADER;进程获得UPGRADER的前提条件是,不能有UPGRADER或WRITER存在,但是当有一个进程获得UPGRADER时,进程无法成功申请READER.
24
25### 2.3 设计的细节
26
27#### 2.3.1 RwLock数据结构
28```rust
29pub struct RwLock<T> {
30    lock: AtomicU32,//原子变量
31    data: UnsafeCell<T>,
32}
33```
34#### 2.3.2 READER守卫的数据结构
35```rust
36pub struct RwLockReadGuard<'a, T: 'a> {
37    data: *const T,
38    lock: &'a AtomicU32,
39}
40```
41
42#### 2.3.3 UPGRADER守卫的数据结构
43```rust
44pub struct RwLockUpgradableGuard<'a, T: 'a> {
45    data: *const T,
46    inner: &'a RwLock<T>,
47}
48```
49
50#### 2.3.4 WRITER守卫的数据结构
51```rust
52pub struct RwLockWriteGuard<'a, T: 'a> {
53    data: *mut T,
54    inner: &'a RwLock<T>,
55}
56```
57
58#### 2.3.5 RwLock的lock的结构介绍
59lock是一个32位原子变量AtomicU32, 它的比特位分配如下:
60```
61                                                       UPGRADER_BIT     WRITER_BIT
62                                                         ^                   ^
63OVERFLOW_BIT                                             +------+    +-------+
64  ^                                                             |    |
65  |                                                             |    |
66+-+--+--------------------------------------------------------+-+--+-+--+
67|    |                                                        |    |    |
68|    |                                                        |    |    |
69|    |             The number of the readers                  |    |    |
70|    |                                                        |    |    |
71+----+--------------------------------------------------------+----+----+
72  31  30                                                    2   1    0
73```
74
75&emsp;&emsp;(从右到左)第0位表征WRITER是否有效,若WRITER_BIT=1, 则存在一个进程获得了WRITER守卫; 若UPGRADER_BIT=1, 则存在一个进程获得了UPGRADER守卫,第2位到第30位用来二进制表示获得READER守卫的进程数; 第31位是溢出判断位, 若OVERFLOW_BIT=1, 则不再接受新的读者守卫的获得申请.
76
77
78## 3.  读写锁的主要API
79### 3.1 RwLock的主要API
80```rust
81///功能:  输入需要保护的数据类型data,返回一个新的RwLock类型.
82pub const fn new(data: T) -> Self
83```
84```rust
85///功能: 获得READER守卫
86pub fn read(&self) -> RwLockReadGuard<T>
87```
88```rust
89///功能: 尝试获得READER守卫
90pub fn try_read(&self) -> Option<RwLockReadGuard<T>>
91```
92```rust
93///功能: 获得WRITER守卫
94pub fn write(&self) -> RwLockWriteGuard<T>
95```
96```rust
97///功能: 尝试获得WRITER守卫
98pub fn try_write(&self) -> Option<RwLockWriteGuard<T>>
99```
100```rust
101///功能: 获得UPGRADER守卫
102pub fn upgradeable_read(&self) -> RwLockUpgradableGuard<T>
103```
104```rust
105///功能: 尝试获得UPGRADER守卫
106pub fn try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>>
107```
108### 3.2 WRITER守卫RwLockWriteGuard的主要API
109```rust
110///功能: 将WRITER降级为READER
111pub fn downgrade(self) -> RwLockReadGuard<'rwlock, T>
112```
113```rust
114///功能: 将WRITER降级为UPGRADER
115pub fn downgrade_to_upgradeable(self) -> RwLockUpgradableGuard<'rwlock, T>
116```
117### 3.3 UPGRADER守卫RwLockUpgradableGuard的主要API
118```rust
119///功能: 将UPGRADER升级为WRITER
120pub fn upgrade(mut self) -> RwLockWriteGuard<'rwlock, T>
121```
122```rust
123///功能: 将UPGRADER降级为READER
124pub fn downgrade(self) -> RwLockReadGuard<'rwlock, T>
125```
126
127## 4. 用法实例
128```rust
129static LOCK: RwLock<u32> = RwLock::new(100 as u32);
130
131fn t_read1() {
132    let guard = LOCK.read();
133    let value = *guard;
134    let readers_current = LOCK.reader_count();
135    let writers_current = LOCK.writer_count();
136    println!(
137        "Reader1: the value is {value}
138    There are totally {writers_current} writers, {readers_current} readers"
139    );
140}
141
142fn t_read2() {
143    let guard = LOCK.read();
144    let value = *guard;
145    let readers_current = LOCK.reader_count();
146    let writers_current = LOCK.writer_count();
147    println!(
148        "Reader2: the value is {value}
149    There are totally {writers_current} writers, {readers_current} readers"
150    );
151}
152
153fn t_write() {
154    let mut guard = LOCK.write();
155    *guard += 100;
156    let writers_current = LOCK.writer_count();
157    let readers_current = LOCK.reader_count();
158    println!(
159        "Writers: the value is {guard}
160    There are totally {writers_current} writers, {readers_current} readers",
161        guard = *guard
162    );
163    let read_guard=guard.downgrade();
164    let value=*read_guard;
165    println!("After downgraded to read_guard: {value}");
166}
167
168fn t_upgrade() {
169    let guard = LOCK.upgradeable_read();
170    let value = *guard;
171    let readers_current = LOCK.reader_count();
172    let writers_current = LOCK.writer_count();
173    println!(
174        "Upgrader1 before upgrade: the value is {value}
175    There are totally {writers_current} writers, {readers_current} readers"
176    );
177    let mut upgraded_guard = guard.upgrade();
178    *upgraded_guard += 100;
179    let writers_current = LOCK.writer_count();
180    let readers_current = LOCK.reader_count();
181    println!(
182        "Upgrader1 after upgrade: the value is {temp}
183    There are totally {writers_current} writers, {readers_current} readers",
184        temp = *upgraded_guard
185    );
186    let downgraded_guard=upgraded_guard.downgrade_to_upgradeable();
187    let value=*downgraded_guard;
188    println!("value after downgraded: {value}");
189    let read_guard=downgraded_guard.downgrade();
190    let value_=*read_guard;
191    println!("value after downgraded to read_guard: {value_}");
192}
193
194fn main() {
195    let r2=thread::spawn(t_read2);
196    let r1 = thread::spawn(t_read1);
197    let t1 = thread::spawn(t_write);
198    let g1 = thread::spawn(t_upgrade);
199    r1.join().expect("r1");
200    t1.join().expect("t1");
201    g1.join().expect("g1");
202    r2.join().expect("r2");
203}
204```