mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2025-07-28 10:48:30 +00:00
refactor: Implement with_lock for lock_api
This commit is contained in:
parent
6d29098d1a
commit
b635e825d2
4 changed files with 29 additions and 3 deletions
|
@ -111,6 +111,7 @@ tracing-subscriber.workspace = true
|
|||
tracing.workspace = true
|
||||
url.workspace = true
|
||||
parking_lot.workspace = true
|
||||
lock_api.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
nix.workspace = true
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub trait WithLock<T> {
|
||||
pub trait WithLock<T: ?Sized> {
|
||||
/// Acquires a lock and executes the given closure with the locked data.
|
||||
fn with_lock<F>(&self, f: F)
|
||||
where
|
||||
|
@ -33,6 +33,30 @@ impl<T> WithLock<T> for Arc<Mutex<T>> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<R: lock_api::RawMutex, T: ?Sized> WithLock<T> for lock_api::Mutex<R, T> {
|
||||
fn with_lock<F>(&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<R: lock_api::RawMutex, T: ?Sized> WithLock<T> for Arc<lock_api::Mutex<R, T>> {
|
||||
fn with_lock<F>(&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<T> {
|
||||
/// Acquires a lock and executes the given closure with the locked data.
|
||||
fn with_lock<F>(&self, f: F) -> impl Future<Output = ()>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue