Expand description

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-std

This crate is compatible with no-std. You just need to provide an implementation of ThreadIdProvider trait for your environment and enable the feature no-std.

use thread_owned_lock::{ThreadIdProvider, ThreadOwnedLock};
struct MYThreadIdProvider{}

impl ThreadIdProvider for MYThreadIdProvider {
    type Id = u32;
    fn current_thread_id() -> Self::Id {
        todo!()
    }
}

type MyThreadOwnedLock<T> = ThreadOwnedLock<T, MYThreadIdProvider>;

Structs§

  • ThreadIdProvider implementation based on std::thread::ThreadId
  • A mutual exclusion primitive similar to Mutex but it only allows the owning thread to access the data.
  • An RAII implementation of a “scoped lock” of a mutex. When this structure is dropped (falls out of scope), the lock will be unlocked.

Enums§

Traits§

  • Trait which abstract what the thread ID is and how it can be obtained.

Type Aliases§