1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#[cfg(all(test, not(target_os = "emscripten")))]
mod tests;

use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::rwlock as sys;

/// reader-writer 锁
///
/// 这种类型的锁定在任何时间点都允许多个 readers 或最多一个 writer。
/// 此锁的写入部分通常允许修改基础数据 (独占访问),而此锁的读取部分通常允许进行只读访问 (共享访问)。
///
///
/// 相比之下,[`Mutex`] 不会区分获取锁定的 readers 或 writers,因此会阻塞等待锁定变为可用的所有线程。
/// `RwLock` 将允许任意数量的 readers 获取锁,只要 writer 不持有该锁即可。
///
/// 锁定的优先级策略取决于基础操作系统的实现,并且这种类型不能保证将使用任何特定的策略。
/// 特别是,等待获取 `write` 中的锁的 writer 可能会也可能不会阻止对 `read` 的并发调用,例如:
///
/// <details><summary>潜在的死锁示例</summary>
///
/// ```text
/// // Thread 1             |  // Thread 2
/// let _rg = lock.read();  |
///                         |  // 会阻塞
///                         |  let _wg = lock.write();
/// // 可能死锁         |
/// let _rg = lock.read();  |
/// ```
/// </details>
///
/// 类型参数 `T` 表示此锁保护的数据。
/// 要求 `T` 满足 [`Send`] 在线程之间共享,并且 [`Sync`] 允许通过 readers 进行并发访问。
/// 从锁定方法返回的 RAII 防护实现 [`Deref`] (对于 `write` 方法为 [`DerefMut`]) 以允许访问锁的内容。
///
/// # Poisoning
///
/// `RwLock` 和 [`Mutex`] 一样,将在 panic 上中毒。
/// 但是请注意,仅当 0panic 处于独占锁定状态 (写模式) 时,`RwLock` 才可能中毒。如果在任何 reader 中出现 panic,则锁不会中毒。
///
/// # Examples
///
/// ```
/// use std::sync::RwLock;
///
/// let lock = RwLock::new(5);
///
/// // 可以一次持有许多 reader 锁
/// {
///     let r1 = lock.read().unwrap();
///     let r2 = lock.read().unwrap();
///     assert_eq!(*r1, 5);
///     assert_eq!(*r2, 5);
/// } // 此时将丢弃读锁
///
/// // 只能持有一个写锁,但是
/// {
///     let mut w = lock.write().unwrap();
///     *w += 1;
///     assert_eq!(*w, 6);
/// } // 写锁在这里被丢弃
/// ```
///
/// [`Mutex`]: super::Mutex
///
///
///
///
///
///
///
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RwLock<T: ?Sized> {
    inner: sys::MovableRWLock,
    poison: poison::Flag,
    data: UnsafeCell<T>,
}

#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Send> Send for RwLock<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Send + Sync> Sync for RwLock<T> {}

/// RAII 结构,用于在丢弃锁时释放锁的共享读取访问。
///
/// 该结构体由 [`RwLock`] 上的 [`read`] 和 [`try_read`] 方法创建。
///
///
/// [`read`]: RwLock::read
/// [`try_read`]: RwLock::try_read
///
#[must_use = "if unused the RwLock will immediately unlock"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
    lock: &'a RwLock<T>,
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Send for RwLockReadGuard<'_, T> {}

#[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
unsafe impl<T: ?Sized + Sync> Sync for RwLockReadGuard<'_, T> {}

/// RAII 结构,用于在锁被丢弃时释放对锁的独占写访问。
///
/// 该结构体由 [`RwLock`] 上的 [`write`] 和 [`try_write`] 方法创建。
///
///
/// [`write`]: RwLock::write
/// [`try_write`]: RwLock::try_write
///
#[must_use = "if unused the RwLock will immediately unlock"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
    lock: &'a RwLock<T>,
    poison: poison::Guard,
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Send for RwLockWriteGuard<'_, T> {}

#[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
unsafe impl<T: ?Sized + Sync> Sync for RwLockWriteGuard<'_, T> {}

impl<T> RwLock<T> {
    /// 创建一个已解锁的 `RwLock<T>` 的新实例。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::RwLock;
    ///
    /// let lock = RwLock::new(5);
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(t: T) -> RwLock<T> {
        RwLock {
            inner: sys::MovableRWLock::new(),
            poison: poison::Flag::new(),
            data: UnsafeCell::new(t),
        }
    }
}

impl<T: ?Sized> RwLock<T> {
    /// 使用共享的读取访问权限锁定此 rwlock,阻塞当前线程,直到可以获取它为止。
    ///
    /// 调用线程将被阻塞,直到没有其他持有该锁的 writers 为止。
    /// 当此方法返回时,锁中可能当前存在其他 readers。
    /// 对于有争议的 readers 或 writers 将首先获取锁的顺序,此方法不提供任何保证。
    ///
    ///
    /// 返回 RAII 保护,一旦该线程被丢弃,它将释放该线程的共享访问。
    ///
    /// # Errors
    ///
    /// 如果 RwLock 中毒,则此函数将返回错误。当 writer panics 持有排他锁时,RwLock 会中毒。
    /// 获取锁定后,将立即发生故障。
    ///
    /// # Panics
    ///
    /// 如果当前线程已锁定,则调用此函数时可能为 panic。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, RwLock};
    /// use std::thread;
    ///
    /// let lock = Arc::new(RwLock::new(1));
    /// let c_lock = Arc::clone(&lock);
    ///
    /// let n = lock.read().unwrap();
    /// assert_eq!(*n, 1);
    ///
    /// thread::spawn(move || {
    ///     let r = c_lock.read();
    ///     assert!(r.is_ok());
    /// }).join().unwrap();
    /// ```
    ///
    ///
    ///
    ///
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
        unsafe {
            self.inner.read();
            RwLockReadGuard::new(self)
        }
    }

    /// 尝试使用共享的读取访问权限来获取此 rwlock。
    ///
    /// 如果此时不能授予访问权限,则返回 `Err`。
    /// 否则,将返回 RAII 保护,当该保护被丢弃时,该保护将释放共享访问。
    ///
    /// 该函数不会阻止。
    ///
    /// 对于有争议的 readers 或 writers 将首先获取锁的顺序,此函数不提供任何保证。
    ///
    ///
    /// # Errors
    ///
    /// 如果 RwLock 中毒,此函数将返回 [`Poisoned`] 错误。
    /// 当 writer panics 持有排他锁时,RwLock 会中毒。
    /// `Poisoned` 仅当以其他方式获取锁时才会返回。
    ///
    /// 如果 RwLock 因为已经被独占锁定而无法获取,该函数将返回 [`WouldBlock`] 错误。
    ///
    /// [`Poisoned`]: TryLockError::Poisoned
    /// [`WouldBlock`]: TryLockError::WouldBlock
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::RwLock;
    ///
    /// let lock = RwLock::new(1);
    ///
    /// match lock.try_read() {
    ///     Ok(n) => assert_eq!(*n, 1),
    ///     Err(_) => unreachable!(),
    /// };
    /// ```
    ///
    ///
    ///
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>> {
        unsafe {
            if self.inner.try_read() {
                Ok(RwLockReadGuard::new(self)?)
            } else {
                Err(TryLockError::WouldBlock)
            }
        }
    }

    /// 用独占式写访问锁定该 rwlock,阻塞当前线程,直到可以获取它为止。
    ///
    /// 当前其他 writers 或其他 readers 可以访问该锁时,此函数将不会返回。
    ///
    ///
    /// 返回一个 RAII 保护,当该保护被丢弃时,它将丢弃该读写锁的写访问。
    ///
    /// # Errors
    ///
    /// 如果 RwLock 中毒,则此函数将返回错误。
    /// 当 writer panics 持有排他锁时,RwLock 会中毒。
    /// 获取锁时将返回错误。
    ///
    /// # Panics
    ///
    /// 如果当前线程已锁定,则调用此函数时可能为 panic。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::RwLock;
    ///
    /// let lock = RwLock::new(1);
    ///
    /// let mut n = lock.write().unwrap();
    /// *n = 2;
    ///
    /// assert!(lock.try_read().is_err());
    /// ```
    ///
    ///
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
        unsafe {
            self.inner.write();
            RwLockWriteGuard::new(self)
        }
    }

    /// 尝试使用互斥写访问权限锁定此 rwlock。
    ///
    /// 如果此时无法获取锁,则返回 `Err`。
    /// 否则,将返回 RAII 守卫,它将在锁被丢弃时释放锁。
    ///
    /// 该函数不会阻止。
    ///
    /// 对于有争议的 readers 或 writers 将首先获取锁的顺序,此函数不提供任何保证。
    ///
    ///
    /// # Errors
    ///
    /// 如果 RwLock 中毒,此函数将返回 [`Poisoned`] 错误。
    /// 当 writer panics 持有排他锁时,RwLock 会中毒。
    /// `Poisoned` 仅当以其他方式获取锁时才会返回。
    ///
    /// 如果 RwLock 因为已经被独占锁定而无法获取,该函数将返回 [`WouldBlock`] 错误。
    ///
    /// [`Poisoned`]: TryLockError::Poisoned
    /// [`WouldBlock`]: TryLockError::WouldBlock
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::RwLock;
    ///
    /// let lock = RwLock::new(1);
    ///
    /// let n = lock.read().unwrap();
    /// assert_eq!(*n, 1);
    ///
    /// assert!(lock.try_write().is_err());
    /// ```
    ///
    ///
    ///
    ///
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>> {
        unsafe {
            if self.inner.try_write() {
                Ok(RwLockWriteGuard::new(self)?)
            } else {
                Err(TryLockError::WouldBlock)
            }
        }
    }

    /// 确定锁是否中毒。
    ///
    /// 如果另一个线程处于活动状态,则锁定仍可能随时中毒。
    /// 如果没有其他同步,则不应信任 `false` 值来确保程序正确性。
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::{Arc, RwLock};
    /// use std::thread;
    ///
    /// let lock = Arc::new(RwLock::new(0));
    /// let c_lock = Arc::clone(&lock);
    ///
    /// let _ = thread::spawn(move || {
    ///     let _lock = c_lock.write().unwrap();
    ///     panic!(); // 锁被毒死了
    /// }).join();
    /// assert_eq!(lock.is_poisoned(), true);
    /// ```
    #[inline]
    #[stable(feature = "sync_poison", since = "1.2.0")]
    pub fn is_poisoned(&self) -> bool {
        self.poison.get()
    }

    /// 消耗此 `RwLock`,返回基础数据。
    ///
    /// # Errors
    ///
    /// 如果 RwLock 中毒,则此函数将返回错误。
    /// 当 writer panics 持有排他锁时,RwLock 会中毒。
    ///
    /// 仅当以其他方式获取锁时,才会返回错误。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::RwLock;
    ///
    /// let lock = RwLock::new(String::new());
    /// {
    ///     let mut s = lock.write().unwrap();
    ///     *s = "modified".to_owned();
    /// }
    /// assert_eq!(lock.into_inner().unwrap(), "modified");
    /// ```
    #[stable(feature = "rwlock_into_inner", since = "1.6.0")]
    pub fn into_inner(self) -> LockResult<T>
    where
        T: Sized,
    {
        let data = self.data.into_inner();
        poison::map_result(self.poison.borrow(), |_| data)
    }

    /// 返回对基础数据的可变引用。
    ///
    /// 由于此调用借用 `RwLock` 是可变的,因此不需要进行实际的锁定 - 可变借用可以静态地保证不存在任何锁定。
    ///
    ///
    /// # Errors
    ///
    /// 如果 RwLock 中毒,则此函数将返回错误。当 writer panics 持有排他锁时,RwLock 会中毒。
    /// 仅当以其他方式获取锁时,才会返回错误。
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::RwLock;
    ///
    /// let mut lock = RwLock::new(0);
    /// *lock.get_mut().unwrap() = 10;
    /// assert_eq!(*lock.read().unwrap(), 10);
    /// ```
    ///
    ///
    #[stable(feature = "rwlock_get_mut", since = "1.6.0")]
    pub fn get_mut(&mut self) -> LockResult<&mut T> {
        let data = self.data.get_mut();
        poison::map_result(self.poison.borrow(), |_| data)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("RwLock");
        match self.try_read() {
            Ok(guard) => {
                d.field("data", &&*guard);
            }
            Err(TryLockError::Poisoned(err)) => {
                d.field("data", &&**err.get_ref());
            }
            Err(TryLockError::WouldBlock) => {
                struct LockedPlaceholder;
                impl fmt::Debug for LockedPlaceholder {
                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        f.write_str("<locked>")
                    }
                }
                d.field("data", &LockedPlaceholder);
            }
        }
        d.field("poisoned", &self.poison.get());
        d.finish_non_exhaustive()
    }
}

#[stable(feature = "rw_lock_default", since = "1.10.0")]
impl<T: Default> Default for RwLock<T> {
    /// 用 T 的 `Default` 值创建一个新的 `RwLock<T>`。
    fn default() -> RwLock<T> {
        RwLock::new(Default::default())
    }
}

#[stable(feature = "rw_lock_from", since = "1.24.0")]
impl<T> From<T> for RwLock<T> {
    /// 创建一个已解锁的 `RwLock<T>` 的新实例。
    /// 这等效于 [`RwLock::new`]。
    fn from(t: T) -> Self {
        RwLock::new(t)
    }
}

impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
    unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockReadGuard<'rwlock, T>> {
        poison::map_result(lock.poison.borrow(), |_| RwLockReadGuard { lock })
    }
}

impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> {
    unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockWriteGuard<'rwlock, T>> {
        poison::map_result(lock.poison.borrow(), |guard| RwLockWriteGuard { lock, poison: guard })
    }
}

#[stable(feature = "std_debug", since = "1.16.0")]
impl<T: fmt::Debug> fmt::Debug for RwLockReadGuard<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T: ?Sized + fmt::Display> fmt::Display for RwLockReadGuard<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

#[stable(feature = "std_debug", since = "1.16.0")]
impl<T: fmt::Debug> fmt::Debug for RwLockWriteGuard<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T: ?Sized + fmt::Display> fmt::Display for RwLockWriteGuard<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.lock.data.get() }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.lock.data.get() }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.lock.data.get() }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Drop for RwLockReadGuard<'_, T> {
    fn drop(&mut self) {
        unsafe {
            self.lock.inner.read_unlock();
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Drop for RwLockWriteGuard<'_, T> {
    fn drop(&mut self) {
        self.lock.poison.done(&self.poison);
        unsafe {
            self.lock.inner.write_unlock();
        }
    }
}