]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/rwlock.rs
Auto merge of #100848 - xfix:use-metadata-for-slice-len, r=thomcc
[rust.git] / library / std / src / sys_common / rwlock.rs
1 use crate::sys::locks as imp;
2
3 /// An OS-based reader-writer lock.
4 ///
5 /// This rwlock cleans up its resources in its `Drop` implementation and may
6 /// safely be moved (when not borrowed).
7 ///
8 /// This rwlock does not implement poisoning.
9 ///
10 /// This is either a wrapper around `LazyBox<imp::RwLock>` or `imp::RwLock`,
11 /// depending on the platform. It is boxed on platforms where `imp::RwLock` may
12 /// not be moved.
13 pub struct MovableRwLock(imp::MovableRwLock);
14
15 impl MovableRwLock {
16     /// Creates a new reader-writer lock for use.
17     #[inline]
18     #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
19     pub const fn new() -> Self {
20         Self(imp::MovableRwLock::new())
21     }
22
23     /// Acquires shared access to the underlying lock, blocking the current
24     /// thread to do so.
25     #[inline]
26     pub fn read(&self) {
27         unsafe { self.0.read() }
28     }
29
30     /// Attempts to acquire shared access to this lock, returning whether it
31     /// succeeded or not.
32     ///
33     /// This function does not block the current thread.
34     #[inline]
35     pub fn try_read(&self) -> bool {
36         unsafe { self.0.try_read() }
37     }
38
39     /// Acquires write access to the underlying lock, blocking the current thread
40     /// to do so.
41     #[inline]
42     pub fn write(&self) {
43         unsafe { self.0.write() }
44     }
45
46     /// Attempts to acquire exclusive access to this lock, returning whether it
47     /// succeeded or not.
48     ///
49     /// This function does not block the current thread.
50     #[inline]
51     pub fn try_write(&self) -> bool {
52         unsafe { self.0.try_write() }
53     }
54
55     /// Unlocks previously acquired shared access to this lock.
56     ///
57     /// Behavior is undefined if the current thread does not have shared access.
58     #[inline]
59     pub unsafe fn read_unlock(&self) {
60         self.0.read_unlock()
61     }
62
63     /// Unlocks previously acquired exclusive access to this lock.
64     ///
65     /// Behavior is undefined if the current thread does not currently have
66     /// exclusive access.
67     #[inline]
68     pub unsafe fn write_unlock(&self) {
69         self.0.write_unlock()
70     }
71 }