mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2025-07-27 10:18: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
1
Cargo.lock
generated
1
Cargo.lock
generated
|
@ -963,6 +963,7 @@ dependencies = [
|
|||
"itertools 0.14.0",
|
||||
"libc",
|
||||
"libloading",
|
||||
"lock_api",
|
||||
"log",
|
||||
"maplit",
|
||||
"nix",
|
||||
|
|
|
@ -519,8 +519,8 @@ version = "1.0"
|
|||
version = "0.12.4"
|
||||
|
||||
# Use this when extending with_lock::WithLock to parking_lot
|
||||
# [workspace.dependencies.lock_api]
|
||||
# version = "0.4.13"
|
||||
[workspace.dependencies.lock_api]
|
||||
version = "0.4.13"
|
||||
|
||||
[workspace.dependencies.bytesize]
|
||||
version = "2.0"
|
||||
|
|
|
@ -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