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.
13 pub const fn new() -> Self {
14 Self(imp::RwLock::new())
17 /// Acquires shared access to the underlying lock, blocking the current
20 /// The lock is automatically unlocked when the returned guard is dropped.
22 pub fn read(&'static self) -> StaticRwLockReadGuard {
23 unsafe { self.0.read() };
24 StaticRwLockReadGuard(&self.0)
27 /// Acquires write access to the underlying lock, blocking the current thread
30 /// The lock is automatically unlocked when the returned guard is dropped.
32 pub fn write(&'static self) -> StaticRwLockWriteGuard {
33 unsafe { self.0.write() };
34 StaticRwLockWriteGuard(&self.0)
39 pub struct StaticRwLockReadGuard(&'static imp::RwLock);
41 impl Drop for StaticRwLockReadGuard {
51 pub struct StaticRwLockWriteGuard(&'static imp::RwLock);
53 impl Drop for StaticRwLockWriteGuard {
57 self.0.write_unlock();
62 /// An OS-based reader-writer lock.
64 /// This rwlock does *not* have a const constructor, cleans up its resources in
65 /// its `Drop` implementation and may safely be moved (when not borrowed).
67 /// This rwlock does not implement poisoning.
69 /// This is either a wrapper around `Box<imp::RwLock>` or `imp::RwLock`,
70 /// depending on the platform. It is boxed on platforms where `imp::RwLock` may
72 pub struct MovableRwLock(imp::MovableRwLock);
75 /// Creates a new reader-writer lock for use.
76 pub fn new() -> Self {
77 Self(imp::MovableRwLock::from(imp::RwLock::new()))
80 /// Acquires shared access to the underlying lock, blocking the current
84 unsafe { self.0.read() }
87 /// Attempts to acquire shared access to this lock, returning whether it
90 /// This function does not block the current thread.
92 pub fn try_read(&self) -> bool {
93 unsafe { self.0.try_read() }
96 /// Acquires write access to the underlying lock, blocking the current thread
100 unsafe { self.0.write() }
103 /// Attempts to acquire exclusive access to this lock, returning whether it
104 /// succeeded or not.
106 /// This function does not block the current thread.
108 pub fn try_write(&self) -> bool {
109 unsafe { self.0.try_write() }
112 /// Unlocks previously acquired shared access to this lock.
114 /// Behavior is undefined if the current thread does not have shared access.
116 pub unsafe fn read_unlock(&self) {
120 /// Unlocks previously acquired exclusive access to this lock.
122 /// Behavior is undefined if the current thread does not currently have
123 /// exclusive access.
125 pub unsafe fn write_unlock(&self) {
126 self.0.write_unlock()
130 impl Drop for MovableRwLock {
132 unsafe { self.0.destroy() };