swmr-barrier: Asymmetric Heavy-Light Barrier
swmr-barrier provides an asymmetric memory barrier for Single-Writer Multi-Reader (SWMR) scenarios. It implements a Heavy Barrier for the writer (cold path) and a Light Barrier for readers (hot path).
On supported platforms (Linux & Windows), the Light Barrier compiles down to a mere compiler fence with zero runtime instruction overhead, while the Heavy Barrier uses OS APIs to ensure global memory visibility.
Features
- Zero-Cost Readers: On supported platforms,
light_barrier()has no runtime CPU instructions (just a compiler fence). - OS-Hardware Acceleration:
- Linux: Directly invokes
syscall(SYS_membarrier, PRIVATE_EXPEDITED)vialibc. - Windows: Uses
FlushProcessWriteBuffers.
- Linux: Directly invokes
- Automatic Fallback: Safely degrades to
std::sync::atomic::fence(SeqCst)on unsupported platforms (macOS, older Linux kernels, older Windows) or if runtime initialization fails. - Loom Support: Built-in support for Loom concurrency testing.
Usage
Add this to your Cargo.toml:
[]
= "0.1"
Example
use ;
use Arc;
use thread;
use ;
Platform Support
| Platform | Implementation | Overhead (Reader) | Overhead (Writer) |
|---|---|---|---|
| Linux (Kernel 4.14+) | syscall(SYS_membarrier, PRIVATE_EXPEDITED) |
Zero (Compiler Fence) | High (IPI Broadcast) |
| Linux (Older Kernels) | fence(SeqCst) fallback |
High (CPU Fence) | High (CPU Fence) |
| Windows (Vista+) | FlushProcessWriteBuffers |
Zero (Compiler Fence) | High (System Call) |
| macOS / Others | fence(SeqCst) |
High (CPU Fence) | High (CPU Fence) |
| Loom | loom::sync::atomic::fence |
Simulated | Simulated |
Note: This crate directly uses libc to invoke syscall(SYS_membarrier, ...) and automatically detects kernel support at runtime. Older Linux kernels (< 4.14) that do not support MEMBARRIER_CMD_PRIVATE_EXPEDITED will fall back to fence(SeqCst).
Loom Testing
To use with Loom, enable the loom feature:
License
This project is 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.