Crate priomutex [] [src]

A mutex where waiting threads to specify a priority.

The API is very similar to std::sync::Mutex. The key difference, of course, is that lock takes a priority. If multiple threads are waiting for the mutex when it's freed, the one which gave the highest priorty will recieve it.

The other difference is that std::sync::Mutex implements Sync but not Clone, whereas priomutex::Mutex implements Clone but not Sync. In practice this means (1) that you don't need to wrap a priomutex in an Arc, and (2) that we can't implement into_inner and get_mut.

use priomutex::Mutex;
use std::sync::mpsc::channel;
use std::thread;

const N: usize = 10;

// Spawn a few threads to increment a shared variable (non-atomically), and
// let the main thread know once all increments are done.
let data = Mutex::new(0);

let (tx, rx) = channel();
for _ in 0..N {
    let (data, tx) = (data.clone(), tx.clone());
    thread::spawn(move || {
        // The shared state can only be accessed once the lock is held.  Here
        // we spin-wait until the lock is acquired.
        let mut data = data.lock(0);
        // Our non-atomic increment is safe because we're the only thread
        // which can access the shared state when the lock is held.
        *data += 1;
        if *data == N {
            tx.send(()).unwrap();
        }
        // the lock is unlocked here when `data` goes out of scope.
    });
}

rx.recv().unwrap();

Poisoning

Currently, priomutexes don't support poisoning; they are not poisoned if the thread holding the lock panics.

Modules

reservable

A spinlock-only mutex with the ability to reserve the lock for another thread.

Structs

Mutex

A mutex which allows waiting threads to specify a priority.

MutexGuard

An RAII guard. Frees the mutex when dropped.