1 use crate::sys::rwlock 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() };