1 use crate::sys::locks as imp;
3 /// An OS-based reader-writer lock, meant for use in static variables.
5 /// This rwlock does not implement poisoning.
7 /// This rwlock has a const constructor ([`StaticRwLock::new`]), does not
8 /// implement `Drop` to cleanup resources.
9 pub struct StaticRwLock(imp::RwLock);
12 /// Creates a new rwlock for use.
14 pub const fn new() -> Self {
15 Self(imp::RwLock::new())
18 /// Acquires shared access to the underlying lock, blocking the current
21 /// The lock is automatically unlocked when the returned guard is dropped.
23 pub fn read(&'static self) -> StaticRwLockReadGuard {
24 unsafe { self.0.read() };
25 StaticRwLockReadGuard(&self.0)
28 /// Acquires write access to the underlying lock, blocking the current thread
31 /// The lock is automatically unlocked when the returned guard is dropped.
33 pub fn write(&'static self) -> StaticRwLockWriteGuard {
34 unsafe { self.0.write() };
35 StaticRwLockWriteGuard(&self.0)
40 pub struct StaticRwLockReadGuard(&'static imp::RwLock);
42 impl Drop for StaticRwLockReadGuard {
52 pub struct StaticRwLockWriteGuard(&'static imp::RwLock);
54 impl Drop for StaticRwLockWriteGuard {
58 self.0.write_unlock();
63 /// An OS-based reader-writer lock.
65 /// This rwlock cleans up its resources in its `Drop` implementation and may
66 /// safely be moved (when not borrowed).
68 /// This rwlock does not implement poisoning.
70 /// This is either a wrapper around `LazyBox<imp::RwLock>` or `imp::RwLock`,
71 /// depending on the platform. It is boxed on platforms where `imp::RwLock` may
73 pub struct MovableRwLock(imp::MovableRwLock);
76 /// Creates a new reader-writer lock for use.
78 pub const fn new() -> Self {
79 Self(imp::MovableRwLock::new())
82 /// Acquires shared access to the underlying lock, blocking the current
86 unsafe { self.0.read() }
89 /// Attempts to acquire shared access to this lock, returning whether it
92 /// This function does not block the current thread.
94 pub fn try_read(&self) -> bool {
95 unsafe { self.0.try_read() }
98 /// Acquires write access to the underlying lock, blocking the current thread
101 pub fn write(&self) {
102 unsafe { self.0.write() }
105 /// Attempts to acquire exclusive access to this lock, returning whether it
106 /// succeeded or not.
108 /// This function does not block the current thread.
110 pub fn try_write(&self) -> bool {
111 unsafe { self.0.try_write() }
114 /// Unlocks previously acquired shared access to this lock.
116 /// Behavior is undefined if the current thread does not have shared access.
118 pub unsafe fn read_unlock(&self) {
122 /// Unlocks previously acquired exclusive access to this lock.
124 /// Behavior is undefined if the current thread does not currently have
125 /// exclusive access.
127 pub unsafe fn write_unlock(&self) {
128 self.0.write_unlock()