hala_sync/api.rs
1use std::{future::Future, task::Context};
2
3/// Any mutex object should implement this trait
4pub trait Lockable {
5 /// RAII scoped lock guard type.
6 type GuardMut<'a>
7 where
8 Self: 'a;
9
10 /// Lock self and returns RAII locker guard object.
11 fn lock(&self) -> Self::GuardMut<'_>;
12
13 /// Attempts to acquire this lock.
14 ///
15 /// If the lock could not be acquired at this time, then `None` is returned.
16 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.
17 fn try_lock(&self) -> Option<Self::GuardMut<'_>>;
18
19 /// Immediately drops the `guard`, and consequently unlocks the `Lockable` object.
20 ///
21 /// The return value is the associated [`Lockable`] object of this `guard`
22 fn unlock(guard: Self::GuardMut<'_>) -> &Self;
23}
24
25pub trait LockableNew: Lockable {
26 type Value;
27 fn new(value: Self::Value) -> Self;
28}
29
30/// A futures-aware lockable mutex object should implement this trait.
31pub trait AsyncLockable {
32 /// RAII scoped lock guard type.
33 ///
34 /// A guard of futures-aware mutex must be able to transfer between threads
35 /// In other words, this guard must not track any thread-specific details
36 type GuardMut<'a>: AsyncGuardMut<'a, Locker = Self> + Send + Unpin
37 where
38 Self: 'a;
39
40 /// Future created by [`lock`](AsyncLockable::lock) function
41 type GuardMutFuture<'a>: Future<Output = Self::GuardMut<'a>> + Send
42 where
43 Self: 'a;
44
45 /// Acquire the lock asynchronously.
46 fn lock(&self) -> Self::GuardMutFuture<'_>;
47
48 /// Immediately drops the `guard`, and consequently unlocks the `Lockable` object.
49 ///
50 /// The return value is the associated [`Lockable`] object of this `guard`
51 fn unlock<'a>(guard: Self::GuardMut<'a>) -> &'a Self;
52}
53
54/// Trait for guard of [`AsyncLockable`]
55pub trait AsyncGuardMut<'a> {
56 type Locker: AsyncLockable<GuardMut<'a> = Self>
57 where
58 Self: 'a;
59}
60
61/// Event manager for [`AsyncLockable`] listeners.
62pub trait AsyncLockableMediator {
63 /// Block the current task and wait for lockable event.
64 ///
65 /// Return the unique wait key.
66 fn wait_lockable(&mut self, cx: &mut Context<'_>) -> usize;
67
68 /// Cancel the waker by key value.
69 /// Returns true if remove waker successfully.
70 fn cancel(&mut self, key: usize) -> bool;
71
72 /// Randomly notify one listener that it can try to lock this mutex again.
73 fn notify_one(&mut self);
74
75 /// notify all listeners that they can try to lock this mutex again.
76 fn notify_all(&mut self);
77}