atomic_shim/lib.rs
1//! Atomic types shims for unsupported architectures
2//!
3//! This crate provides shims for `std::sync::AtomicU64` and `std::sync::AtomicI64` for `mips` and `powerpc`.
4//!
5//! The `std` primitives are not available on all platforms, and that makes it tricky to write code for `mips`, such as OpenWRT Routers.
6//! This crate provides it's own `AtomicU64` and `AtomicI64`, which can directly replace the `std::sync` structs.
7//!
8//! The crate does target detection and on supported architectures it will use `std::sync` structures.
9//! When it detects it is running on unsupported platforms, it fallbacks to the shim implementation, using `crossbeam` Mutex.
10//!
11//! For testing purposes, and for other reasons, you can replace the default implementation with the Mutex implementation by using the `features = ["mutex"]`
12//!
13//! # Usage
14//!
15//! Replace any imports of `use std::sync::AtomicU64;` with `use atomic_shim::Atomic64;`
16//!
17//! # Examples
18//!
19//! A simple spinlock:
20//!
21//! ```
22//! use std::sync::Arc;
23//! use std::sync::atomic::Ordering;
24//! use std::thread;
25//! use atomic_shim::AtomicU64;
26//!
27//!
28//! let spinlock = Arc::new(AtomicU64::new(1));
29//!
30//! let spinlock_clone = spinlock.clone();
31//! let thread = thread::spawn(move|| {
32//! spinlock_clone.store(0, Ordering::SeqCst);
33//! });
34//!
35//! // Wait for the other thread to release the lock
36//! while spinlock.load(Ordering::SeqCst) != 0 {}
37//!
38//! if let Err(panic) = thread.join() {
39//! println!("Thread had an error: {:?}", panic);
40//! }
41//!```
42//!
43//! Keep a global count of live threads:
44//!
45//! ```
46//! use std::sync::atomic::Ordering;
47//! use atomic_shim::AtomicU64;
48//!
49//! let global_thread_count = AtomicU64::new(0);
50//!
51//! let old_thread_count = global_thread_count.fetch_add(1, Ordering::SeqCst);
52//! println!("live threads: {}", old_thread_count + 1);
53//! ```
54
55#[cfg(not(any(target_arch = "mips", target_arch = "powerpc", feature = "mutex")))]
56pub use std::sync::atomic::{AtomicI64, AtomicU64};
57
58#[cfg(any(target_arch = "mips", target_arch = "powerpc", feature = "mutex"))]
59mod shim;
60
61#[cfg(any(target_arch = "mips", target_arch = "powerpc", feature = "mutex"))]
62pub use shim::{AtomicI64, AtomicU64};