Skip to main content

Mutex

Struct Mutex 

Source
pub struct Mutex<P: Priority, T: ?Sized, Q: MutexQueue<P> = DefaultMutexQueue<P>> { /* private fields */ }
Expand description

A mutex that queues waiters by priority. Higher priority requesters will receive access first.

If the evict feature is enabled, the current holder of the lock will be notified if a higher priority waiter is queued.

Note that requesters with the same priority may receive their access in an arbitrary priority - if this is non-desireable, FIFO and LIFO may be used.

Example:

use async_priority_lock::{FIFO, HighestFirst, Mutex, MutexGuard};

static MY_LOCK: Mutex<FIFO<HighestFirst<usize>>, Vec<usize>> =
    Mutex::const_new(vec![]);

async fn push_num(num: usize, priority: usize) {
    // Pushes our number to the queue.  If multiple writers are waiting on this, the waiters
    // will acquire access by order of priority.  As the priority is FIFO, rquesters with the
    // same priority will execute oldest first.
    MY_LOCK.lock_from(priority).await.push(num);
}

async fn wait_and_push(num: usize, priority: usize) {
    loop {
        let mut guard = MY_LOCK.lock_from(priority).await;
        // wait a second or abort and retry if the resource is requested with a higher
        // priority in the meantime
        tokio::select! {
            _ = tokio::time::sleep(tokio::time::Duration::from_secs(1)) => {},
            _ = MutexGuard::evicted(&mut guard) => {
                // drop the guard and try again
                continue;
            }
        }

        guard.push(num)
    }
}

Implementations§

Source§

impl<P: Priority, T: ?Sized, Q: MutexQueue<P>> Mutex<P, T, Q>

Source

pub fn try_lock( &self, priority: impl Into<P>, ) -> Result<MutexGuard<'_, P, T, Q>, TryLockError>

Try to acquire the lock without blocking or requesting eviction of the current holder.

Priority will be stored in guard; higher priority requesters will try to evict the returned guard if the evict flag is enabled.

i.e. the holder may wait / check for eviction via MutexGuard::evicted.

Source

pub async fn lock(&self, priority: P) -> MutexGuard<'_, P, T, Q>

Acquire exclusive access to the locked resource, waiting until after higher priority requesters acquire and release the lock.

If the evict feature is enabled, this will also notify the current holder to request it to release the lock if the current holder is lower priority.

i.e. the holder may wait / check for eviction via MutexGuard::evicted.

Cancel Safety: This function is cancel safe.

Source

pub fn lock_from( &self, priority: impl Into<P>, ) -> impl Future<Output = MutexGuard<'_, P, T, Q>>

Acquire exclusive access to the locked resource, waiting until higher priority requesters release the lock.

Shorthand for self.lock(priority.into()).

Cancel Safety: This function is cancel safe.

Source

pub fn lock_default(&self) -> impl Future<Output = MutexGuard<'_, P, T, Q>>
where P: Default,

Acquire exclusive access to the locked resource, waiting until higher priority requesters release the lock.

Shorthand for self.lock(Default::default()).

Cancel Safety: This function is cancel safe.

Source

pub fn new(val: T) -> Self
where T: Sized,

Create a new Mutex, unlocked and ready for use.

Source

pub const fn const_new(val: T) -> Self
where Q: ConstDefault, T: Sized,

Create a new Mutex, unlocked and ready for use.

Available when the queue is ConstDefault if the const-default feature is enabled.

All builtin queues are ConstDefault.

Trait Implementations§

Source§

impl<P: Priority, T: ConstDefault, Q: ConstDefault + MutexQueue<P>> ConstDefault for Mutex<P, T, Q>

Available on crate feature const-default only.
Source§

const DEFAULT: Self

The constant default value.
Source§

impl<P, T, Q: MutexQueue<P>> Debug for Mutex<P, T, Q>
where T: Debug + ?Sized, P: Default + Priority,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<P: Priority, T: Default, Q: MutexQueue<P>> Default for Mutex<P, T, Q>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, P: Priority, T, Q: MutexQueue<P>> Deserialize<'de> for Mutex<P, T, Q>
where T: Deserialize<'de>,

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<P: Priority, T: ?Sized + Send, Q: Send + MutexQueue<P>> Send for Mutex<P, T, Q>

Source§

impl<P: Priority, T: ?Sized + Send, Q: Send + Sync + MutexQueue<P>> Sync for Mutex<P, T, Q>

For the mutex to be Sync, T must be Send (Sync is not needed).

Also see rust Mutex docs

(however, both Sync and Send are required for the queue; usually these are implemented if P is Send + Sync)

Source§

impl<P: Priority, T: ?Sized + Unpin, Q: Unpin + MutexQueue<P>> Unpin for Mutex<P, T, Q>

Auto Trait Implementations§

§

impl<P, T, Q = ArenaQueue<SingleLinkArenaQueueNode<MutexWaiter<P>>>> !Freeze for Mutex<P, T, Q>

§

impl<P, T, Q = ArenaQueue<SingleLinkArenaQueueNode<MutexWaiter<P>>>> !RefUnwindSafe for Mutex<P, T, Q>

§

impl<P, T, Q> UnsafeUnpin for Mutex<P, T, Q>
where T: UnsafeUnpin + ?Sized, Q: UnsafeUnpin,

§

impl<P, T, Q> UnwindSafe for Mutex<P, T, Q>
where P: UnwindSafe, T: UnwindSafe + ?Sized,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,