A unified, trait-based abstraction over threading and memory-sharing models for Rust.
thread-model allows library authors to write code that is generic over its concurrency requirements. By programming against the ThreadModel trait, your logic can switch between single-threaded (high performance, no atomic overhead) and multi-threaded (thread-safe, atomic) implementations without changing a single line of business logic.
- Generic Reference Counting: Support for
Rc<T>vsArc<T>(andWeakpointers). - Abstracted Locking: Unified interface for
MutexandRwLockviaparking_lot'sRawMutex/RawRwLocktraits. - Generic Atomics: Powered by
radium, allowing seamless switching betweenAtom<T>andRadon<T>. - Plug-and-Play: Built-in implementations for
ThreadSafe(usingArc/Atom/parking_lot) andThreadLocal(usingRc/Radon/RefCell).
If you are familiar with the archery crate:
- Similarities: Both crates aim to solve the problem of being generic over
RcandArc. - The Difference:
archeryfocuses primarily on the pointer wrapper (SharedPtr<T, P>).thread-modeltakes a broader approach by abstracting the entire environment. - Beyond Pointers: While
archeryhandles reference counting,thread-modelalso abstracts Locking mechanisms (Mutexes/RwLocks) and Atomic Cells. This makes it a more comprehensive tool for building entire frameworks (like ECS or Actor systems) that need to be portable between sync and async/local-thread contexts.
Add this to your Cargo.toml:
[dependencies]
thread-model = "0.1.0"use thread_model::{ThreadModel, RefCounter};
pub struct MyComponent<M: ThreadModel> {
data: RefCounter<M, String>,
lock: M::RawMutex,
}
impl<M: ThreadModel> MyComponent<M> {
pub fn new(val: String) -> Self {
// Implementation remains the same regardless of the model
}
}Single-threaded (No atomic overhead):
use thread_model::ThreadLocal;
let local_comp = MyComponent::<ThreadLocal>::new("Local".into());Multi-threaded (Thread-safe):
use thread_model::ThreadSafe;
let safe_comp = MyComponent::<ThreadSafe>::new("Safe".into());The crate provides three core modules:
ThreadModel: The core trait defining associated types forRefCounter,AtomicCell,RawMutex, etc.ThreadSafe: An implementation usingstd::sync::Arc,parking_lotlocks, and atomic operations.ThreadLocal: An implementation usingstd::rc::Rc,RefCell-based "locks", and non-atomic operations (viaradium::Radon).
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.