[][src]Struct piper::Lock

pub struct Lock<T>(_);

An asynchronous lock.

This type is similar to [std::sync::Mutex], except locking is an asynchronous operation.

Note that [Lock] by itself acts like an [Arc] in the sense that cloning it returns just another reference to the same lock.

Furthermore, [LockGuard] is not tied to [Lock] by a lifetime, so you can keep guards for as long as you want. This is useful when you want to spawn a task and move a guard into its future.

Examples

use piper::Lock;
use smol::Task;

let lock = Lock::new(0);
let mut tasks = vec![];

for _ in 0..10 {
    let lock = lock.clone();
    tasks.push(Task::spawn(async move { *lock.lock().await += 1 }));
}

for task in tasks {
    task.await;
}
assert_eq!(*lock.lock().await, 10);

Methods

impl<T> Lock<T>[src]

pub fn new(data: T) -> Lock<T>[src]

Creates a new async lock.

Examples

use piper::Lock;

let lock = Lock::new(0);

pub async fn lock<'_>(&'_ self) -> LockGuard<T>[src]

Acquires the lock.

Returns a guard that releases the lock when dropped.

Examples

use piper::Lock;

let lock = Lock::new(10);
let guard = lock.lock().await;
assert_eq!(*guard, 10);

pub fn try_lock(&self) -> Option<LockGuard<T>>[src]

Attempts to acquire the lock.

If the lock could not be acquired at this time, then [None] is returned. Otherwise, a guard is returned that releases the lock when dropped.

Examples

use piper::Lock;

let lock = Lock::new(10);
if let Some(guard) = lock.try_lock() {
    assert_eq!(*guard, 10);
}

Trait Implementations

impl<T> Clone for Lock<T>[src]

impl<T: Debug> Debug for Lock<T>[src]

impl<T: Default> Default for Lock<T>[src]

impl<T> From<T> for Lock<T>[src]

impl<T: Send> Send for Lock<T>[src]

impl<T: Send> Sync for Lock<T>[src]

Auto Trait Implementations

impl<T> !RefUnwindSafe for Lock<T>

impl<T> Unpin for Lock<T>

impl<T> !UnwindSafe for Lock<T>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<!> for T[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.