Crates.io | thread-owned-lock |
lib.rs | thread-owned-lock |
version | 0.1.0 |
source | src |
created_at | 2024-03-06 07:41:48.059593 |
updated_at | 2024-03-06 07:41:48.059593 |
description | Mutex which can only be unlocked by the owning thread. |
homepage | |
repository | https://gitlab.com/AngryPixel/threadownedlock |
max_upload_size | |
id | 1164453 |
size | 15,222 |
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.
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.
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.
}
});