Mutex

Type Alias Mutex 

Source
pub type Mutex<T> = Lock<T, MutexBackend>;
Expand description

A mutual exclusion primitive.

Exposes the kernel’s struct mutex. When multiple threads attempt to lock the same mutex, only one at a time is allowed to progress, the others will block (sleep) until the mutex is unlocked, at which point another thread will be allowed to wake up and make progress.

Since it may block, Mutex needs to be used with care in atomic contexts.

Instances of Mutex need a lock class and to be pinned. The recommended way to create such instances is with the pin_init and new_mutex macros.

§Examples

The following example shows how to declare, allocate and initialise a struct (Example) that contains an inner struct (Inner) that is protected by a mutex.

use kernel::sync::{new_mutex, Mutex};

struct Inner {
    a: u32,
    b: u32,
}

#[pin_data]
struct Example {
    c: u32,
    #[pin]
    d: Mutex<Inner>,
}

impl Example {
    fn new() -> impl PinInit<Self> {
        pin_init!(Self {
            c: 10,
            d <- new_mutex!(Inner { a: 20, b: 30 }),
        })
    }
}

// Allocate a boxed `Example`.
let e = KBox::pin_init(Example::new(), GFP_KERNEL)?;
assert_eq!(e.c, 10);
assert_eq!(e.d.lock().a, 20);
assert_eq!(e.d.lock().b, 30);

The following example shows how to use interior mutability to modify the contents of a struct protected by a mutex despite only having a shared reference:

use kernel::sync::Mutex;

struct Example {
    a: u32,
    b: u32,
}

fn example(m: &Mutex<Example>) {
    let mut guard = m.lock();
    guard.a += 10;
    guard.b += 20;
}

Aliased Type§

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

Trait Implementations§

Source§

impl<T: BinaryReaderMut + Unpin> BinaryReader for Mutex<T>

Source§

fn read_from_slice( &self, reader: &mut UserSliceReader, offset: &mut Offset, ) -> Result<usize>

Reads the binary form of self from reader. Read more
Source§

impl<T: BinaryWriter> BinaryWriter for Mutex<T>

Source§

fn write_to_slice( &self, writer: &mut UserSliceWriter, offset: &mut Offset, ) -> Result<usize>

Writes the binary form of self into writer. Read more
Source§

impl<T: FromStr + Unpin> Reader for Mutex<T>

Source§

fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result

Updates the value from the given user slice.
Source§

impl<T: Writer> Writer for Mutex<T>

Source§

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

Formats the value using the given formatter.