thread-owned-lock

Crates.iothread-owned-lock
lib.rsthread-owned-lock
version0.1.0
sourcesrc
created_at2024-03-06 07:41:48.059593
updated_at2024-03-06 07:41:48.059593
descriptionMutex which can only be unlocked by the owning thread.
homepage
repositoryhttps://gitlab.com/AngryPixel/threadownedlock
max_upload_size
id1164453
size15,222
LeanderBB (LeanderBB)

documentation

README

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.
    }
});
Commit count: 0

cargo fmt