1 pub use ::alloc::sync::Arc;
2 use core::ops::{Deref, DerefMut};
3 use core::time::Duration;
4 use core::cell::{RefCell, Ref, RefMut};
5 use super::{LockTestExt, LockHeldState};
7 pub type LockResult<Guard> = Result<Guard, ()>;
12 pub fn new() -> Condvar {
16 pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
21 pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, _dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
25 pub fn notify_all(&self) {}
28 pub struct Mutex<T: ?Sized> {
32 #[must_use = "if unused the Mutex will immediately unlock"]
33 pub struct MutexGuard<'a, T: ?Sized + 'a> {
37 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
40 fn deref(&self) -> &T {
45 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
46 fn deref_mut(&mut self) -> &mut T {
52 pub fn new(inner: T) -> Mutex<T> {
53 Mutex { inner: RefCell::new(inner) }
56 pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
57 Ok(MutexGuard { lock: self.inner.borrow_mut() })
60 pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
61 Ok(MutexGuard { lock: self.inner.borrow_mut() })
65 impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
67 fn held_by_thread(&self) -> LockHeldState {
68 if self.lock().is_err() { return LockHeldState::HeldByThread; }
69 else { return LockHeldState::NotHeldByThread; }
71 type ExclLock = MutexGuard<'a, T>;
73 fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> { self.lock().unwrap() }
76 pub struct RwLock<T: ?Sized> {
80 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
84 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
88 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
91 fn deref(&self) -> &T {
96 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
99 fn deref(&self) -> &T {
104 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
105 fn deref_mut(&mut self) -> &mut T {
106 self.lock.deref_mut()
111 pub fn new(inner: T) -> RwLock<T> {
112 RwLock { inner: RefCell::new(inner) }
115 pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
116 Ok(RwLockReadGuard { lock: self.inner.borrow() })
119 pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
120 Ok(RwLockWriteGuard { lock: self.inner.borrow_mut() })
123 pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
124 match self.inner.try_borrow_mut() {
125 Ok(lock) => Ok(RwLockWriteGuard { lock }),
131 impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
133 fn held_by_thread(&self) -> LockHeldState {
134 if self.write().is_err() { return LockHeldState::HeldByThread; }
135 else { return LockHeldState::NotHeldByThread; }
137 type ExclLock = RwLockWriteGuard<'a, T>;
139 fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> { self.write().unwrap() }
142 pub type FairRwLock<T> = RwLock<T>;