swmr-barrier

Crates.ioswmr-barrier
lib.rsswmr-barrier
version0.1.4
created_at2025-11-27 10:23:09.910389+00
updated_at2025-12-26 06:27:59.344267+00
descriptionAsymmetric Heavy-Light memory barriers for Single-Writer Multi-Reader (SWMR) scenarios, optimized for zero-cost readers.
homepagehttps://github.com/ShaoG-R/swmr-barrier
repositoryhttps://github.com/ShaoG-R/swmr-barrier
max_upload_size
id1953471
size67,414
Shao G. (shaogme)

documentation

https://docs.rs/swmr-barrier

README

swmr-barrier: Asymmetric Heavy-Light Barrier

Crates.io Documentation License

中文文档

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 (requires libc on Linux or windows-sys on Windows).
  • OS-Hardware Acceleration:
    • Linux: Directly invokes syscall(SYS_membarrier, PRIVATE_EXPEDITED) via libc.
    • Windows: Dynamically resolves FlushProcessWriteBuffers at runtime (safe fallback for older OS).
  • Minimal Dependencies: Does not rely on the ctor crate. Uses #[unsafe(link_section = ...)] for zero-overhead, automatic initialization before main.
  • 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:

[dependencies]
swmr-barrier = "0.1"

Example

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use swmr_barrier::{heavy_barrier, light_barrier};

fn main() {
    let x = Arc::new(AtomicUsize::new(0));
    let y = Arc::new(AtomicUsize::new(0));

    let x_writer = x.clone();
    let y_writer = y.clone();

    // Writer Thread (Cold Path)
    let writer = thread::spawn(move || {
        x_writer.store(1, Ordering::Relaxed);
        
        // Heavy Barrier: Ensures X is visible before Y
        // Cost: High (IPI on Linux, System Call on Windows)
        heavy_barrier();
        
        y_writer.store(1, Ordering::Relaxed);
    });

    // Reader Thread (Hot Path)
    let reader = thread::spawn(move || {
        // Wait for Y to be set
        while y.load(Ordering::Relaxed) == 0 {
            std::hint::spin_loop();
        }

        // Light Barrier: Ensures if we see Y, we must see X
        // Cost: Zero (Compiler Fence only) on supported platforms
        light_barrier();

        let x_val = x.load(Ordering::Relaxed);
        assert_eq!(x_val, 1, "X must be 1 if Y is 1");
    });

    writer.join().unwrap();
    reader.join().unwrap();
}

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:

cargo test --features loom

License

This project is licensed under either of

at your option.

Commit count: 0

cargo fmt