Struct Mutex

Source
pub struct Mutex<T> { /* private fields */ }
Expand description

An async mutex. This is similar to the Mutex type in the standard library, but it is async.

This type only implements Sync when T is Send. Values are provided through the Deref and DerefMut implementations on the Guard type.

§Examples

use no_std_async::Mutex;

static COUNT: Mutex<u8> = Mutex::new(0);

// These functions will each trade the lock, counting it up to infinity (in this case, u8::MAX).

async fn task_1() {
    loop {
        let mut count = COUNT.lock().await;
        if *count == u8::MAX {
            break;
        }
        let expected = *count + 1;
        *count += 1;
        assert_eq!(expected, *count); // we have the lock, so our value can't be modified otherwise.
    }
}

async fn task_2() {
   loop {
      let mut count = COUNT.lock().await;
      if *count == u8::MAX {
          break;
      }
      let expected = *count + 1;
      *count += 1;
      assert_eq!(expected, *count); // we have the lock, so our value can't be modified otherwise.
  }
}

Implementations§

Source§

impl<T> Mutex<T>

Source

pub const fn new(data: T) -> Self

Creates a new Mutex with the given data.

Source

pub async fn lock<'a>(&'a self) -> Guard<'a, T>
where T: 'a,

Acquires a lock on the data.

Trait Implementations§

Source§

impl<T: Send> Send for Mutex<T>

Source§

impl<T: Send> Sync for Mutex<T>

Auto Trait Implementations§

§

impl<T> !Freeze for Mutex<T>

§

impl<T> !RefUnwindSafe for Mutex<T>

§

impl<T> Unpin for Mutex<T>
where T: Unpin,

§

impl<T> !UnwindSafe for Mutex<T>

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.