1 use std::{ops, sync}; 2 3 /// A synchronous mutual exclusion primitive useful for protecting shared data. 4 #[derive(Default, Debug)] 5 pub struct Mutex<T>(sync::Mutex<T>); 6 7 impl<T> Mutex<T> { 8 /// Creates a new mutex in an unlocked state ready for use. new(value: T) -> Self9 pub fn new(value: T) -> Self { 10 Self(sync::Mutex::new(value)) 11 } 12 13 /// Acquires a mutex, blocking the current thread until it is able to do so. lock(&self) -> MutexGuard<'_, T>14 pub fn lock(&self) -> MutexGuard<'_, T> { 15 let guard = self.0.lock().unwrap(); 16 17 MutexGuard(guard) 18 } 19 20 /// Consumes this mutex, returning the underlying data. into_inner(self) -> T21 pub fn into_inner(self) -> T { 22 self.0.into_inner().unwrap() 23 } 24 } 25 26 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is 27 /// dropped (falls out of scope), the lock will be unlocked. 28 pub struct MutexGuard<'a, T>(sync::MutexGuard<'a, T>); 29 30 impl<'a, T> ops::Deref for MutexGuard<'a, T> { 31 type Target = T; 32 deref(&self) -> &Self::Target33 fn deref(&self) -> &Self::Target { 34 &self.0 35 } 36 } 37 38 impl<'a, T> ops::DerefMut for MutexGuard<'a, T> { deref_mut(&mut self) -> &mut Self::Target39 fn deref_mut(&mut self) -> &mut Self::Target { 40 &mut self.0 41 } 42 } 43 44 /// A synchronous reader-writer lock. 45 #[derive(Default, Debug)] 46 pub struct RwLock<T>(sync::RwLock<T>); 47 48 impl<T> RwLock<T> { 49 /// Creates a new mutex in an unlocked state ready for use. new(value: T) -> Self50 pub fn new(value: T) -> Self { 51 Self(sync::RwLock::new(value)) 52 } 53 54 /// Locks this rwlock with shared read access, blocking the current thread 55 /// until it can be acquired. read(&self) -> RwLockReadGuard<'_, T>56 pub fn read(&self) -> RwLockReadGuard<'_, T> { 57 let guard = self.0.read().unwrap(); 58 59 RwLockReadGuard(guard) 60 } 61 62 /// Locks this rwlock with exclusive write access, blocking the current 63 /// thread until it can be acquired. write(&self) -> RwLockWriteGuard<'_, T>64 pub fn write(&self) -> RwLockWriteGuard<'_, T> { 65 let guard = self.0.write().unwrap(); 66 67 RwLockWriteGuard(guard) 68 } 69 } 70 71 /// RAII structure used to release the shared read access of a lock when 72 /// dropped. 73 pub struct RwLockReadGuard<'a, T>(sync::RwLockReadGuard<'a, T>); 74 75 impl<'a, T> ops::Deref for RwLockReadGuard<'a, T> { 76 type Target = T; 77 deref(&self) -> &Self::Target78 fn deref(&self) -> &Self::Target { 79 &self.0 80 } 81 } 82 83 /// RAII structure used to release the exclusive write access of a lock when 84 /// dropped. 85 pub struct RwLockWriteGuard<'a, T>(sync::RwLockWriteGuard<'a, T>); 86 87 impl<'a, T> ops::Deref for RwLockWriteGuard<'a, T> { 88 type Target = T; 89 deref(&self) -> &Self::Target90 fn deref(&self) -> &Self::Target { 91 &self.0 92 } 93 } 94 95 impl<'a, T> ops::DerefMut for RwLockWriteGuard<'a, T> { deref_mut(&mut self) -> &mut Self::Target96 fn deref_mut(&mut self) -> &mut Self::Target { 97 &mut self.0 98 } 99 } 100