#thread #mutex #lock #shared-data #access #owning

no-std thread-owned-lock

Mutex which can only be unlocked by the owning thread

1 unstable release

0.1.0 Mar 6, 2024

#923 in Concurrency

MIT license

14KB
182 lines

Thread Owned Lock

This crates provides a concurrency primitive similar to Mutex but only allows the currently bound thread to access its contents. Unlike Mutex it does not cause a thread to block if another thread has acquired the lock, but the operation will fail immediately.

The primitive also ensures that the owning thread can only acquire the lock once in order to not break Rust's aliasing rules.

Use Case

This concurrency primitive is useful to enforce that only one specific thread can access the data within. Depending on your OS, it may also be faster that a regular Mutex. You can run this crate's benchmark to check how it fairs on your machine.

Example

use std::sync::RwLock;
use thread_owned_lock::StdThreadOwnedLock;

struct SharedData {
    main_thread_data: StdThreadOwnedLock<i32>,
    shared_data: RwLock<i32>,
}

let shared_data = std::sync::Arc::new(SharedData {
    main_thread_data: StdThreadOwnedLock::new(20),
    shared_data:RwLock::new(30)
});
{
    let guard = shared_data.main_thread_data.lock();
    // Main thread can now access the contents;
}
let data_cloned = shared_data.clone();
std::thread::spawn(move|| {
    if let Err(e) = data_cloned.main_thread_data.try_lock() {
        // On other threads, accessing the main thread data will fail.
    }
});

No runtime deps