//! Traits for explicitly scoping the lifetime of locks. use std::sync::{Arc, Mutex}; pub trait WithLock { /// Acquires a lock and executes the given closure with the locked data. fn with_lock(&self, f: F) where F: FnMut(&mut T); } impl WithLock for Mutex { fn with_lock(&self, mut f: F) where F: FnMut(&mut T), { // The locking and unlocking logic is hidden inside this function. let mut data_guard = self.lock().unwrap(); f(&mut data_guard); // Lock is released here when `data_guard` goes out of scope. } } impl WithLock for Arc> { fn with_lock(&self, mut f: F) where F: FnMut(&mut T), { // The locking and unlocking logic is hidden inside this function. let mut data_guard = self.lock().unwrap(); f(&mut data_guard); // Lock is released here when `data_guard` goes out of scope. } } impl WithLock for lock_api::Mutex { fn with_lock(&self, mut f: F) where F: FnMut(&mut T), { // The locking and unlocking logic is hidden inside this function. let mut data_guard = self.lock(); f(&mut data_guard); // Lock is released here when `data_guard` goes out of scope. } } impl WithLock for Arc> { fn with_lock(&self, mut f: F) where F: FnMut(&mut T), { // The locking and unlocking logic is hidden inside this function. let mut data_guard = self.lock(); f(&mut data_guard); // Lock is released here when `data_guard` goes out of scope. } } pub trait WithLockAsync { /// Acquires a lock and executes the given closure with the locked data. fn with_lock(&self, f: F) -> impl Future where F: FnMut(&mut T); } impl WithLockAsync for futures::lock::Mutex { async fn with_lock(&self, mut f: F) where F: FnMut(&mut T), { // The locking and unlocking logic is hidden inside this function. let mut data_guard = self.lock().await; f(&mut data_guard); // Lock is released here when `data_guard` goes out of scope. } } impl WithLockAsync for Arc> { async fn with_lock(&self, mut f: F) where F: FnMut(&mut T), { // The locking and unlocking logic is hidden inside this function. let mut data_guard = self.lock().await; f(&mut data_guard); // Lock is released here when `data_guard` goes out of scope. } }