1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cell::UnsafeCell;
6 use crate::ops::{Deref, DerefMut};
7 use crate::ptr::NonNull;
8 use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
9 use crate::sys_common::rwlock as sys;
11 /// A reader-writer lock
13 /// This type of lock allows a number of readers or at most one writer at any
14 /// point in time. The write portion of this lock typically allows modification
15 /// of the underlying data (exclusive access) and the read portion of this lock
16 /// typically allows for read-only access (shared access).
18 /// In comparison, a [`Mutex`] does not distinguish between readers or writers
19 /// that acquire the lock, therefore blocking any threads waiting for the lock to
20 /// become available. An `RwLock` will allow any number of readers to acquire the
21 /// lock as long as a writer is not holding the lock.
23 /// The priority policy of the lock is dependent on the underlying operating
24 /// system's implementation, and this type does not guarantee that any
25 /// particular policy will be used. In particular, a writer which is waiting to
26 /// acquire the lock in `write` might or might not block concurrent calls to
29 /// <details><summary>Potential deadlock example</summary>
32 /// // Thread 1 | // Thread 2
33 /// let _rg = lock.read(); |
35 /// | let _wg = lock.write();
37 /// let _rg = lock.read(); |
41 /// The type parameter `T` represents the data that this lock protects. It is
42 /// required that `T` satisfies [`Send`] to be shared across threads and
43 /// [`Sync`] to allow concurrent access through readers. The RAII guards
44 /// returned from the locking methods implement [`Deref`] (and [`DerefMut`]
45 /// for the `write` methods) to allow access to the content of the lock.
49 /// An `RwLock`, like [`Mutex`], will become poisoned on a panic. Note, however,
50 /// that an `RwLock` may only be poisoned if a panic occurs while it is locked
51 /// exclusively (write mode). If a panic occurs in any reader, then the lock
52 /// will not be poisoned.
57 /// use std::sync::RwLock;
59 /// let lock = RwLock::new(5);
61 /// // many reader locks can be held at once
63 /// let r1 = lock.read().unwrap();
64 /// let r2 = lock.read().unwrap();
65 /// assert_eq!(*r1, 5);
66 /// assert_eq!(*r2, 5);
67 /// } // read locks are dropped at this point
69 /// // only one write lock may be held, however
71 /// let mut w = lock.write().unwrap();
73 /// assert_eq!(*w, 6);
74 /// } // write lock is dropped here
77 /// [`Mutex`]: super::Mutex
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct RwLock<T: ?Sized> {
80 inner: sys::MovableRwLock,
85 #[stable(feature = "rust1", since = "1.0.0")]
86 unsafe impl<T: ?Sized + Send> Send for RwLock<T> {}
87 #[stable(feature = "rust1", since = "1.0.0")]
88 unsafe impl<T: ?Sized + Send + Sync> Sync for RwLock<T> {}
90 /// RAII structure used to release the shared read access of a lock when
93 /// This structure is created by the [`read`] and [`try_read`] methods on
96 /// [`read`]: RwLock::read
97 /// [`try_read`]: RwLock::try_read
98 #[must_use = "if unused the RwLock will immediately unlock"]
99 #[must_not_suspend = "holding a RwLockReadGuard across suspend \
100 points can cause deadlocks, delays, \
101 and cause Futures to not implement `Send`"]
102 #[stable(feature = "rust1", since = "1.0.0")]
103 #[clippy::has_significant_drop]
104 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
106 inner_lock: &'a sys::MovableRwLock,
109 #[stable(feature = "rust1", since = "1.0.0")]
110 impl<T: ?Sized> !Send for RwLockReadGuard<'_, T> {}
112 #[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
113 unsafe impl<T: ?Sized + Sync> Sync for RwLockReadGuard<'_, T> {}
115 /// RAII structure used to release the exclusive write access of a lock when
118 /// This structure is created by the [`write`] and [`try_write`] methods
121 /// [`write`]: RwLock::write
122 /// [`try_write`]: RwLock::try_write
123 #[must_use = "if unused the RwLock will immediately unlock"]
124 #[must_not_suspend = "holding a RwLockWriteGuard across suspend \
125 points can cause deadlocks, delays, \
126 and cause Future's to not implement `Send`"]
127 #[stable(feature = "rust1", since = "1.0.0")]
128 #[clippy::has_significant_drop]
129 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
131 poison: poison::Guard,
134 #[stable(feature = "rust1", since = "1.0.0")]
135 impl<T: ?Sized> !Send for RwLockWriteGuard<'_, T> {}
137 #[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
138 unsafe impl<T: ?Sized + Sync> Sync for RwLockWriteGuard<'_, T> {}
141 /// Creates a new instance of an `RwLock<T>` which is unlocked.
146 /// use std::sync::RwLock;
148 /// let lock = RwLock::new(5);
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub fn new(t: T) -> RwLock<T> {
153 inner: sys::MovableRwLock::new(),
154 poison: poison::Flag::new(),
155 data: UnsafeCell::new(t),
160 impl<T: ?Sized> RwLock<T> {
161 /// Locks this rwlock with shared read access, blocking the current thread
162 /// until it can be acquired.
164 /// The calling thread will be blocked until there are no more writers which
165 /// hold the lock. There may be other readers currently inside the lock when
166 /// this method returns. This method does not provide any guarantees with
167 /// respect to the ordering of whether contentious readers or writers will
168 /// acquire the lock first.
170 /// Returns an RAII guard which will release this thread's shared access
171 /// once it is dropped.
175 /// This function will return an error if the RwLock is poisoned. An RwLock
176 /// is poisoned whenever a writer panics while holding an exclusive lock.
177 /// The failure will occur immediately after the lock has been acquired.
181 /// This function might panic when called if the lock is already held by the current thread.
186 /// use std::sync::{Arc, RwLock};
189 /// let lock = Arc::new(RwLock::new(1));
190 /// let c_lock = Arc::clone(&lock);
192 /// let n = lock.read().unwrap();
193 /// assert_eq!(*n, 1);
195 /// thread::spawn(move || {
196 /// let r = c_lock.read();
197 /// assert!(r.is_ok());
198 /// }).join().unwrap();
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
205 RwLockReadGuard::new(self)
209 /// Attempts to acquire this rwlock with shared read access.
211 /// If the access could not be granted at this time, then `Err` is returned.
212 /// Otherwise, an RAII guard is returned which will release the shared access
213 /// when it is dropped.
215 /// This function does not block.
217 /// This function does not provide any guarantees with respect to the ordering
218 /// of whether contentious readers or writers will acquire the lock first.
222 /// This function will return the [`Poisoned`] error if the RwLock is poisoned.
223 /// An RwLock is poisoned whenever a writer panics while holding an exclusive
224 /// lock. `Poisoned` will only be returned if the lock would have otherwise been
227 /// This function will return the [`WouldBlock`] error if the RwLock could not
228 /// be acquired because it was already locked exclusively.
230 /// [`Poisoned`]: TryLockError::Poisoned
231 /// [`WouldBlock`]: TryLockError::WouldBlock
236 /// use std::sync::RwLock;
238 /// let lock = RwLock::new(1);
240 /// match lock.try_read() {
241 /// Ok(n) => assert_eq!(*n, 1),
242 /// Err(_) => unreachable!(),
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>> {
249 if self.inner.try_read() {
250 Ok(RwLockReadGuard::new(self)?)
252 Err(TryLockError::WouldBlock)
257 /// Locks this rwlock with exclusive write access, blocking the current
258 /// thread until it can be acquired.
260 /// This function will not return while other writers or other readers
261 /// currently have access to the lock.
263 /// Returns an RAII guard which will drop the write access of this rwlock
268 /// This function will return an error if the RwLock is poisoned. An RwLock
269 /// is poisoned whenever a writer panics while holding an exclusive lock.
270 /// An error will be returned when the lock is acquired.
274 /// This function might panic when called if the lock is already held by the current thread.
279 /// use std::sync::RwLock;
281 /// let lock = RwLock::new(1);
283 /// let mut n = lock.write().unwrap();
286 /// assert!(lock.try_read().is_err());
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
293 RwLockWriteGuard::new(self)
297 /// Attempts to lock this rwlock with exclusive write access.
299 /// If the lock could not be acquired at this time, then `Err` is returned.
300 /// Otherwise, an RAII guard is returned which will release the lock when
303 /// This function does not block.
305 /// This function does not provide any guarantees with respect to the ordering
306 /// of whether contentious readers or writers will acquire the lock first.
310 /// This function will return the [`Poisoned`] error if the RwLock is
311 /// poisoned. An RwLock is poisoned whenever a writer panics while holding
312 /// an exclusive lock. `Poisoned` will only be returned if the lock would have
313 /// otherwise been acquired.
315 /// This function will return the [`WouldBlock`] error if the RwLock could not
316 /// be acquired because it was already locked exclusively.
318 /// [`Poisoned`]: TryLockError::Poisoned
319 /// [`WouldBlock`]: TryLockError::WouldBlock
325 /// use std::sync::RwLock;
327 /// let lock = RwLock::new(1);
329 /// let n = lock.read().unwrap();
330 /// assert_eq!(*n, 1);
332 /// assert!(lock.try_write().is_err());
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>> {
338 if self.inner.try_write() {
339 Ok(RwLockWriteGuard::new(self)?)
341 Err(TryLockError::WouldBlock)
346 /// Determines whether the lock is poisoned.
348 /// If another thread is active, the lock can still become poisoned at any
349 /// time. You should not trust a `false` value for program correctness
350 /// without additional synchronization.
355 /// use std::sync::{Arc, RwLock};
358 /// let lock = Arc::new(RwLock::new(0));
359 /// let c_lock = Arc::clone(&lock);
361 /// let _ = thread::spawn(move || {
362 /// let _lock = c_lock.write().unwrap();
363 /// panic!(); // the lock gets poisoned
365 /// assert_eq!(lock.is_poisoned(), true);
368 #[stable(feature = "sync_poison", since = "1.2.0")]
369 pub fn is_poisoned(&self) -> bool {
373 /// Clear the poisoned state from a lock
375 /// If the lock is poisoned, it will remain poisoned until this function is called. This allows
376 /// recovering from a poisoned state and marking that it has recovered. For example, if the
377 /// value is overwritten by a known-good value, then the mutex can be marked as un-poisoned. Or
378 /// possibly, the value could be inspected to determine if it is in a consistent state, and if
379 /// so the poison is removed.
384 /// #![feature(mutex_unpoison)]
386 /// use std::sync::{Arc, RwLock};
389 /// let lock = Arc::new(RwLock::new(0));
390 /// let c_lock = Arc::clone(&lock);
392 /// let _ = thread::spawn(move || {
393 /// let _lock = c_lock.write().unwrap();
394 /// panic!(); // the mutex gets poisoned
397 /// assert_eq!(lock.is_poisoned(), true);
398 /// let guard = lock.write().unwrap_or_else(|mut e| {
399 /// **e.get_mut() = 1;
400 /// lock.clear_poison();
403 /// assert_eq!(lock.is_poisoned(), false);
404 /// assert_eq!(*guard, 1);
407 #[unstable(feature = "mutex_unpoison", issue = "96469")]
408 pub fn clear_poison(&self) {
412 /// Consumes this `RwLock`, returning the underlying data.
416 /// This function will return an error if the RwLock is poisoned. An RwLock
417 /// is poisoned whenever a writer panics while holding an exclusive lock. An
418 /// error will only be returned if the lock would have otherwise been
424 /// use std::sync::RwLock;
426 /// let lock = RwLock::new(String::new());
428 /// let mut s = lock.write().unwrap();
429 /// *s = "modified".to_owned();
431 /// assert_eq!(lock.into_inner().unwrap(), "modified");
433 #[stable(feature = "rwlock_into_inner", since = "1.6.0")]
434 pub fn into_inner(self) -> LockResult<T>
438 let data = self.data.into_inner();
439 poison::map_result(self.poison.borrow(), |()| data)
442 /// Returns a mutable reference to the underlying data.
444 /// Since this call borrows the `RwLock` mutably, no actual locking needs to
445 /// take place -- the mutable borrow statically guarantees no locks exist.
449 /// This function will return an error if the RwLock is poisoned. An RwLock
450 /// is poisoned whenever a writer panics while holding an exclusive lock. An
451 /// error will only be returned if the lock would have otherwise been
457 /// use std::sync::RwLock;
459 /// let mut lock = RwLock::new(0);
460 /// *lock.get_mut().unwrap() = 10;
461 /// assert_eq!(*lock.read().unwrap(), 10);
463 #[stable(feature = "rwlock_get_mut", since = "1.6.0")]
464 pub fn get_mut(&mut self) -> LockResult<&mut T> {
465 let data = self.data.get_mut();
466 poison::map_result(self.poison.borrow(), |()| data)
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473 let mut d = f.debug_struct("RwLock");
474 match self.try_read() {
476 d.field("data", &&*guard);
478 Err(TryLockError::Poisoned(err)) => {
479 d.field("data", &&**err.get_ref());
481 Err(TryLockError::WouldBlock) => {
482 struct LockedPlaceholder;
483 impl fmt::Debug for LockedPlaceholder {
484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485 f.write_str("<locked>")
488 d.field("data", &LockedPlaceholder);
491 d.field("poisoned", &self.poison.get());
492 d.finish_non_exhaustive()
496 #[stable(feature = "rw_lock_default", since = "1.10.0")]
497 impl<T: Default> Default for RwLock<T> {
498 /// Creates a new `RwLock<T>`, with the `Default` value for T.
499 fn default() -> RwLock<T> {
500 RwLock::new(Default::default())
504 #[stable(feature = "rw_lock_from", since = "1.24.0")]
505 impl<T> From<T> for RwLock<T> {
506 /// Creates a new instance of an `RwLock<T>` which is unlocked.
507 /// This is equivalent to [`RwLock::new`].
508 fn from(t: T) -> Self {
513 impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
514 /// Create a new instance of `RwLockReadGuard<T>` from a `RwLock<T>`.
516 /// It is safe to call this function if and only if `lock.inner.read()` (or
517 /// `lock.inner.try_read()`) has been successfully called before instantiating this object.
518 unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockReadGuard<'rwlock, T>> {
519 poison::map_result(lock.poison.borrow(), |()| RwLockReadGuard {
520 data: NonNull::new_unchecked(lock.data.get()),
521 inner_lock: &lock.inner,
526 impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> {
527 /// Create a new instance of `RwLockWriteGuard<T>` from a `RwLock<T>`.
529 /// It is safe to call this function if and only if `lock.inner.write()` (or
530 /// `lock.inner.try_write()`) has been successfully called before instantiating this object.
531 unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockWriteGuard<'rwlock, T>> {
532 poison::map_result(lock.poison.guard(), |guard| RwLockWriteGuard { lock, poison: guard })
536 #[stable(feature = "std_debug", since = "1.16.0")]
537 impl<T: fmt::Debug> fmt::Debug for RwLockReadGuard<'_, T> {
538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543 #[stable(feature = "std_guard_impls", since = "1.20.0")]
544 impl<T: ?Sized + fmt::Display> fmt::Display for RwLockReadGuard<'_, T> {
545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 #[stable(feature = "std_debug", since = "1.16.0")]
551 impl<T: fmt::Debug> fmt::Debug for RwLockWriteGuard<'_, T> {
552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557 #[stable(feature = "std_guard_impls", since = "1.20.0")]
558 impl<T: ?Sized + fmt::Display> fmt::Display for RwLockWriteGuard<'_, T> {
559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
568 fn deref(&self) -> &T {
569 unsafe { self.data.as_ref() }
573 #[stable(feature = "rust1", since = "1.0.0")]
574 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
577 fn deref(&self) -> &T {
578 unsafe { &*self.lock.data.get() }
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
584 fn deref_mut(&mut self) -> &mut T {
585 unsafe { &mut *self.lock.data.get() }
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<T: ?Sized> Drop for RwLockReadGuard<'_, T> {
593 self.inner_lock.read_unlock();
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl<T: ?Sized> Drop for RwLockWriteGuard<'_, T> {
601 self.lock.poison.done(&self.poison);
603 self.lock.inner.write_unlock();