1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cell::UnsafeCell;
7 use crate::ops::{Deref, DerefMut};
9 use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
10 use crate::sys_common::rwlock as sys;
12 /// A reader-writer lock
14 /// This type of lock allows a number of readers or at most one writer at any
15 /// point in time. The write portion of this lock typically allows modification
16 /// of the underlying data (exclusive access) and the read portion of this lock
17 /// typically allows for read-only access (shared access).
19 /// In comparison, a [`Mutex`] does not distinguish between readers or writers
20 /// that acquire the lock, therefore blocking any threads waiting for the lock to
21 /// become available. An `RwLock` will allow any number of readers to acquire the
22 /// lock as long as a writer is not holding the lock.
24 /// The priority policy of the lock is dependent on the underlying operating
25 /// system's implementation, and this type does not guarantee that any
26 /// particular policy will be used.
28 /// The type parameter `T` represents the data that this lock protects. It is
29 /// required that `T` satisfies [`Send`] to be shared across threads and
30 /// [`Sync`] to allow concurrent access through readers. The RAII guards
31 /// returned from the locking methods implement [`Deref`] (and [`DerefMut`]
32 /// for the `write` methods) to allow access to the content of the lock.
36 /// An `RwLock`, like [`Mutex`], will become poisoned on a panic. Note, however,
37 /// that an `RwLock` may only be poisoned if a panic occurs while it is locked
38 /// exclusively (write mode). If a panic occurs in any reader, then the lock
39 /// will not be poisoned.
44 /// use std::sync::RwLock;
46 /// let lock = RwLock::new(5);
48 /// // many reader locks can be held at once
50 /// let r1 = lock.read().unwrap();
51 /// let r2 = lock.read().unwrap();
52 /// assert_eq!(*r1, 5);
53 /// assert_eq!(*r2, 5);
54 /// } // read locks are dropped at this point
56 /// // only one write lock may be held, however
58 /// let mut w = lock.write().unwrap();
60 /// assert_eq!(*w, 6);
61 /// } // write lock is dropped here
64 /// [`Mutex`]: super::Mutex
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct RwLock<T: ?Sized> {
67 inner: Box<sys::RWLock>,
72 #[stable(feature = "rust1", since = "1.0.0")]
73 unsafe impl<T: ?Sized + Send> Send for RwLock<T> {}
74 #[stable(feature = "rust1", since = "1.0.0")]
75 unsafe impl<T: ?Sized + Send + Sync> Sync for RwLock<T> {}
77 /// RAII structure used to release the shared read access of a lock when
80 /// This structure is created by the [`read`] and [`try_read`] methods on
83 /// [`read`]: RwLock::read
84 /// [`try_read`]: RwLock::try_read
85 #[must_use = "if unused the RwLock will immediately unlock"]
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
91 #[stable(feature = "rust1", since = "1.0.0")]
92 impl<T: ?Sized> !Send for RwLockReadGuard<'_, T> {}
94 #[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
95 unsafe impl<T: ?Sized + Sync> Sync for RwLockReadGuard<'_, T> {}
97 /// RAII structure used to release the exclusive write access of a lock when
100 /// This structure is created by the [`write`] and [`try_write`] methods
103 /// [`write`]: RwLock::write
104 /// [`try_write`]: RwLock::try_write
105 #[must_use = "if unused the RwLock will immediately unlock"]
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
109 poison: poison::Guard,
112 #[stable(feature = "rust1", since = "1.0.0")]
113 impl<T: ?Sized> !Send for RwLockWriteGuard<'_, T> {}
115 #[stable(feature = "rwlock_guard_sync", since = "1.23.0")]
116 unsafe impl<T: ?Sized + Sync> Sync for RwLockWriteGuard<'_, T> {}
119 /// Creates a new instance of an `RwLock<T>` which is unlocked.
124 /// use std::sync::RwLock;
126 /// let lock = RwLock::new(5);
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub fn new(t: T) -> RwLock<T> {
131 inner: box sys::RWLock::new(),
132 poison: poison::Flag::new(),
133 data: UnsafeCell::new(t),
138 impl<T: ?Sized> RwLock<T> {
139 /// Locks this rwlock with shared read access, blocking the current thread
140 /// until it can be acquired.
142 /// The calling thread will be blocked until there are no more writers which
143 /// hold the lock. There may be other readers currently inside the lock when
144 /// this method returns. This method does not provide any guarantees with
145 /// respect to the ordering of whether contentious readers or writers will
146 /// acquire the lock first.
148 /// Returns an RAII guard which will release this thread's shared access
149 /// once it is dropped.
153 /// This function will return an error if the RwLock is poisoned. An RwLock
154 /// is poisoned whenever a writer panics while holding an exclusive lock.
155 /// The failure will occur immediately after the lock has been acquired.
159 /// This function might panic when called if the lock is already held by the current thread.
164 /// use std::sync::{Arc, RwLock};
167 /// let lock = Arc::new(RwLock::new(1));
168 /// let c_lock = lock.clone();
170 /// let n = lock.read().unwrap();
171 /// assert_eq!(*n, 1);
173 /// thread::spawn(move || {
174 /// let r = c_lock.read();
175 /// assert!(r.is_ok());
176 /// }).join().unwrap();
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
183 RwLockReadGuard::new(self)
187 /// Attempts to acquire this rwlock with shared read access.
189 /// If the access could not be granted at this time, then `Err` is returned.
190 /// Otherwise, an RAII guard is returned which will release the shared access
191 /// when it is dropped.
193 /// This function does not block.
195 /// This function does not provide any guarantees with respect to the ordering
196 /// of whether contentious readers or writers will acquire the lock first.
200 /// This function will return an error if the RwLock is poisoned. An RwLock
201 /// is poisoned whenever a writer panics while holding an exclusive lock. An
202 /// error will only be returned if the lock would have otherwise been
208 /// use std::sync::RwLock;
210 /// let lock = RwLock::new(1);
212 /// match lock.try_read() {
213 /// Ok(n) => assert_eq!(*n, 1),
214 /// Err(_) => unreachable!(),
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>> {
221 if self.inner.try_read() {
222 Ok(RwLockReadGuard::new(self)?)
224 Err(TryLockError::WouldBlock)
229 /// Locks this rwlock with exclusive write access, blocking the current
230 /// thread until it can be acquired.
232 /// This function will not return while other writers or other readers
233 /// currently have access to the lock.
235 /// Returns an RAII guard which will drop the write access of this rwlock
240 /// This function will return an error if the RwLock is poisoned. An RwLock
241 /// is poisoned whenever a writer panics while holding an exclusive lock.
242 /// An error will be returned when the lock is acquired.
246 /// This function might panic when called if the lock is already held by the current thread.
251 /// use std::sync::RwLock;
253 /// let lock = RwLock::new(1);
255 /// let mut n = lock.write().unwrap();
258 /// assert!(lock.try_read().is_err());
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
265 RwLockWriteGuard::new(self)
269 /// Attempts to lock this rwlock with exclusive write access.
271 /// If the lock could not be acquired at this time, then `Err` is returned.
272 /// Otherwise, an RAII guard is returned which will release the lock when
275 /// This function does not block.
277 /// This function does not provide any guarantees with respect to the ordering
278 /// of whether contentious readers or writers will acquire the lock first.
282 /// This function will return an error if the RwLock is poisoned. An RwLock
283 /// is poisoned whenever a writer panics while holding an exclusive lock. An
284 /// error will only be returned if the lock would have otherwise been
290 /// use std::sync::RwLock;
292 /// let lock = RwLock::new(1);
294 /// let n = lock.read().unwrap();
295 /// assert_eq!(*n, 1);
297 /// assert!(lock.try_write().is_err());
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>> {
303 if self.inner.try_write() {
304 Ok(RwLockWriteGuard::new(self)?)
306 Err(TryLockError::WouldBlock)
311 /// Determines whether the lock is poisoned.
313 /// If another thread is active, the lock can still become poisoned at any
314 /// time. You should not trust a `false` value for program correctness
315 /// without additional synchronization.
320 /// use std::sync::{Arc, RwLock};
323 /// let lock = Arc::new(RwLock::new(0));
324 /// let c_lock = lock.clone();
326 /// let _ = thread::spawn(move || {
327 /// let _lock = c_lock.write().unwrap();
328 /// panic!(); // the lock gets poisoned
330 /// assert_eq!(lock.is_poisoned(), true);
333 #[stable(feature = "sync_poison", since = "1.2.0")]
334 pub fn is_poisoned(&self) -> bool {
338 /// Consumes this `RwLock`, returning the underlying data.
342 /// This function will return an error if the RwLock is poisoned. An RwLock
343 /// is poisoned whenever a writer panics while holding an exclusive lock. An
344 /// error will only be returned if the lock would have otherwise been
350 /// use std::sync::RwLock;
352 /// let lock = RwLock::new(String::new());
354 /// let mut s = lock.write().unwrap();
355 /// *s = "modified".to_owned();
357 /// assert_eq!(lock.into_inner().unwrap(), "modified");
359 #[stable(feature = "rwlock_into_inner", since = "1.6.0")]
360 pub fn into_inner(self) -> LockResult<T>
364 // We know statically that there are no outstanding references to
365 // `self` so there's no need to lock the inner lock.
367 // To get the inner value, we'd like to call `data.into_inner()`,
368 // but because `RwLock` impl-s `Drop`, we can't move out of it, so
369 // we'll have to destructure it manually instead.
371 // Like `let RwLock { inner, poison, data } = self`.
372 let (inner, poison, data) = {
373 let RwLock { ref inner, ref poison, ref data } = self;
374 (ptr::read(inner), ptr::read(poison), ptr::read(data))
377 inner.destroy(); // Keep in sync with the `Drop` impl.
380 poison::map_result(poison.borrow(), |_| data.into_inner())
384 /// Returns a mutable reference to the underlying data.
386 /// Since this call borrows the `RwLock` mutably, no actual locking needs to
387 /// take place -- the mutable borrow statically guarantees no locks exist.
391 /// This function will return an error if the RwLock is poisoned. An RwLock
392 /// is poisoned whenever a writer panics while holding an exclusive lock. An
393 /// error will only be returned if the lock would have otherwise been
399 /// use std::sync::RwLock;
401 /// let mut lock = RwLock::new(0);
402 /// *lock.get_mut().unwrap() = 10;
403 /// assert_eq!(*lock.read().unwrap(), 10);
405 #[stable(feature = "rwlock_get_mut", since = "1.6.0")]
406 pub fn get_mut(&mut self) -> LockResult<&mut T> {
407 // We know statically that there are no other references to `self`, so
408 // there's no need to lock the inner lock.
409 let data = unsafe { &mut *self.data.get() };
410 poison::map_result(self.poison.borrow(), |_| data)
414 #[stable(feature = "rust1", since = "1.0.0")]
415 unsafe impl<#[may_dangle] T: ?Sized> Drop for RwLock<T> {
417 // IMPORTANT: This code needs to be kept in sync with `RwLock::into_inner`.
418 unsafe { self.inner.destroy() }
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 match self.try_read() {
426 Ok(guard) => f.debug_struct("RwLock").field("data", &&*guard).finish(),
427 Err(TryLockError::Poisoned(err)) => {
428 f.debug_struct("RwLock").field("data", &&**err.get_ref()).finish()
430 Err(TryLockError::WouldBlock) => {
431 struct LockedPlaceholder;
432 impl fmt::Debug for LockedPlaceholder {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 f.write_str("<locked>")
438 f.debug_struct("RwLock").field("data", &LockedPlaceholder).finish()
444 #[stable(feature = "rw_lock_default", since = "1.10.0")]
445 impl<T: Default> Default for RwLock<T> {
446 /// Creates a new `RwLock<T>`, with the `Default` value for T.
447 fn default() -> RwLock<T> {
448 RwLock::new(Default::default())
452 #[stable(feature = "rw_lock_from", since = "1.24.0")]
453 impl<T> From<T> for RwLock<T> {
454 /// Creates a new instance of an `RwLock<T>` which is unlocked.
455 /// This is equivalent to [`RwLock::new`].
456 fn from(t: T) -> Self {
461 impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
462 unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockReadGuard<'rwlock, T>> {
463 poison::map_result(lock.poison.borrow(), |_| RwLockReadGuard { lock })
467 impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> {
468 unsafe fn new(lock: &'rwlock RwLock<T>) -> LockResult<RwLockWriteGuard<'rwlock, T>> {
469 poison::map_result(lock.poison.borrow(), |guard| RwLockWriteGuard { lock, poison: guard })
473 #[stable(feature = "std_debug", since = "1.16.0")]
474 impl<T: fmt::Debug> fmt::Debug for RwLockReadGuard<'_, T> {
475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476 f.debug_struct("RwLockReadGuard").field("lock", &self.lock).finish()
480 #[stable(feature = "std_guard_impls", since = "1.20.0")]
481 impl<T: ?Sized + fmt::Display> fmt::Display for RwLockReadGuard<'_, T> {
482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 #[stable(feature = "std_debug", since = "1.16.0")]
488 impl<T: fmt::Debug> fmt::Debug for RwLockWriteGuard<'_, T> {
489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490 f.debug_struct("RwLockWriteGuard").field("lock", &self.lock).finish()
494 #[stable(feature = "std_guard_impls", since = "1.20.0")]
495 impl<T: ?Sized + fmt::Display> fmt::Display for RwLockWriteGuard<'_, T> {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501 #[stable(feature = "rust1", since = "1.0.0")]
502 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
505 fn deref(&self) -> &T {
506 unsafe { &*self.lock.data.get() }
510 #[stable(feature = "rust1", since = "1.0.0")]
511 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
514 fn deref(&self) -> &T {
515 unsafe { &*self.lock.data.get() }
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
521 fn deref_mut(&mut self) -> &mut T {
522 unsafe { &mut *self.lock.data.get() }
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl<T: ?Sized> Drop for RwLockReadGuard<'_, T> {
530 self.lock.inner.read_unlock();
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl<T: ?Sized> Drop for RwLockWriteGuard<'_, T> {
538 self.lock.poison.done(&self.poison);
540 self.lock.inner.write_unlock();