1 pub use ::alloc::sync::Arc;
2 use core::ops::{Deref, DerefMut};
3 use core::time::Duration;
5 use std::collections::HashSet;
6 use std::cell::RefCell;
8 use std::sync::atomic::{AtomicUsize, Ordering};
10 use std::sync::Mutex as StdMutex;
11 use std::sync::MutexGuard as StdMutexGuard;
12 use std::sync::RwLock as StdRwLock;
13 use std::sync::RwLockReadGuard as StdRwLockReadGuard;
14 use std::sync::RwLockWriteGuard as StdRwLockWriteGuard;
15 use std::sync::Condvar as StdCondvar;
17 #[cfg(feature = "backtrace")]
18 use backtrace::Backtrace;
20 pub type LockResult<Guard> = Result<Guard, ()>;
27 pub fn new() -> Condvar {
28 Condvar { inner: StdCondvar::new() }
31 pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
32 let mutex: &'a Mutex<T> = guard.mutex;
33 self.inner.wait(guard.into_inner()).map(|lock| MutexGuard { mutex, lock }).map_err(|_| ())
37 pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
38 let mutex = guard.mutex;
39 self.inner.wait_timeout(guard.into_inner(), dur).map(|(lock, _)| (MutexGuard { mutex, lock }, ())).map_err(|_| ())
42 pub fn notify_all(&self) { self.inner.notify_all(); }
46 /// We track the set of locks currently held by a reference to their `MutexMetadata`
47 static MUTEXES_HELD: RefCell<HashSet<Arc<MutexMetadata>>> = RefCell::new(HashSet::new());
49 static MUTEX_IDX: AtomicUsize = AtomicUsize::new(0);
51 /// Metadata about a single mutex, by id, the set of things locked-before it, and the backtrace of
52 /// when the Mutex itself was constructed.
53 struct MutexMetadata {
55 locked_before: StdMutex<HashSet<Arc<MutexMetadata>>>,
56 #[cfg(feature = "backtrace")]
57 mutex_construction_bt: Backtrace,
59 impl PartialEq for MutexMetadata {
60 fn eq(&self, o: &MutexMetadata) -> bool { self.mutex_idx == o.mutex_idx }
62 impl Eq for MutexMetadata {}
63 impl std::hash::Hash for MutexMetadata {
64 fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) { hasher.write_u64(self.mutex_idx); }
68 fn new() -> MutexMetadata {
70 locked_before: StdMutex::new(HashSet::new()),
71 mutex_idx: MUTEX_IDX.fetch_add(1, Ordering::Relaxed) as u64,
72 #[cfg(feature = "backtrace")]
73 mutex_construction_bt: Backtrace::new(),
77 fn pre_lock(this: &Arc<MutexMetadata>) {
78 MUTEXES_HELD.with(|held| {
79 // For each mutex which is currently locked, check that no mutex's locked-before
80 // set includes the mutex we're about to lock, which would imply a lockorder
82 for locked in held.borrow().iter() {
83 for locked_dep in locked.locked_before.lock().unwrap().iter() {
84 if *locked_dep == *this {
85 #[cfg(feature = "backtrace")]
86 panic!("Tried to violate existing lockorder.\nMutex that should be locked after the current lock was created at the following backtrace.\nNote that to get a backtrace for the lockorder violation, you should set RUST_BACKTRACE=1\n{:?}", locked.mutex_construction_bt);
87 #[cfg(not(feature = "backtrace"))]
88 panic!("Tried to violate existing lockorder. Build with the backtrace feature for more info.");
91 // Insert any already-held mutexes in our locked-before set.
92 this.locked_before.lock().unwrap().insert(Arc::clone(locked));
94 held.borrow_mut().insert(Arc::clone(this));
98 fn try_locked(this: &Arc<MutexMetadata>) {
99 MUTEXES_HELD.with(|held| {
100 // Since a try-lock will simply fail if the lock is held already, we do not
101 // consider try-locks to ever generate lockorder inversions. However, if a try-lock
102 // succeeds, we do consider it to have created lockorder dependencies.
103 for locked in held.borrow().iter() {
104 this.locked_before.lock().unwrap().insert(Arc::clone(locked));
106 held.borrow_mut().insert(Arc::clone(this));
111 pub struct Mutex<T: Sized> {
113 deps: Arc<MutexMetadata>,
116 #[must_use = "if unused the Mutex will immediately unlock"]
117 pub struct MutexGuard<'a, T: Sized + 'a> {
119 lock: StdMutexGuard<'a, T>,
122 impl<'a, T: Sized> MutexGuard<'a, T> {
123 fn into_inner(self) -> StdMutexGuard<'a, T> {
124 // Somewhat unclear why we cannot move out of self.lock, but doing so gets E0509.
126 let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
127 std::mem::forget(self);
133 impl<T: Sized> Drop for MutexGuard<'_, T> {
135 MUTEXES_HELD.with(|held| {
136 held.borrow_mut().remove(&self.mutex.deps);
141 impl<T: Sized> Deref for MutexGuard<'_, T> {
144 fn deref(&self) -> &T {
149 impl<T: Sized> DerefMut for MutexGuard<'_, T> {
150 fn deref_mut(&mut self) -> &mut T {
151 self.lock.deref_mut()
156 pub fn new(inner: T) -> Mutex<T> {
157 Mutex { inner: StdMutex::new(inner), deps: Arc::new(MutexMetadata::new()) }
160 pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
161 MutexMetadata::pre_lock(&self.deps);
162 self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
165 pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
166 let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
168 MutexMetadata::try_locked(&self.deps);
174 pub struct RwLock<T: ?Sized> {
178 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
179 lock: StdRwLockReadGuard<'a, T>,
182 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
183 lock: StdRwLockWriteGuard<'a, T>,
186 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
189 fn deref(&self) -> &T {
194 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
197 fn deref(&self) -> &T {
202 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
203 fn deref_mut(&mut self) -> &mut T {
204 self.lock.deref_mut()
209 pub fn new(inner: T) -> RwLock<T> {
210 RwLock { inner: StdRwLock::new(inner) }
213 pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
214 self.inner.read().map(|lock| RwLockReadGuard { lock }).map_err(|_| ())
217 pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
218 self.inner.write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
221 pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
222 self.inner.try_write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())