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). - no_std Compatible: The core library is
#![no_std], making it suitable for embedded or kernel-level programming (requireslibcon Linux orwindows-syson Windows). - OS-Hardware Acceleration:
- Linux: Directly invokes
syscall(SYS_membarrier, PRIVATE_EXPEDITED)vialibc. - Windows: Dynamically resolves
FlushProcessWriteBuffersat runtime (safe fallback for older OS).
- Linux: Directly invokes
- Minimal Dependencies: Does not rely on the
ctorcrate. Uses#[unsafe(link_section = ...)]for zero-overhead, automatic initialization beforemain. - 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 (Kernel 4.3+) | syscall(SYS_membarrier, SHARED) |
Zero (Compiler Fence) | High (IPI Broadcast) |
| Linux (Pre 4.3) | 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 (using .init_array on Linux and .CRT$XCU on Windows for early initialization). Older Linux kernels that do not support MEMBARRIER_CMD_PRIVATE_EXPEDITED (pre-4.14) will try MEMBARRIER_CMD_SHARED (4.3+). Kernels older than 4.3 or Windows versions older than Vista 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.