fetch_or Sets Atomic Bit Flags

AtomicU32::fetch_or sets a bit and returns the prior value, so concurrent tasks claim status flags exactly once without holding a mutex.

RustData Integrity

Code

rustsnippet
23 lines
use std::sync::atomic::{AtomicU32, Ordering};

const READY: u32 = 1 << 0;
const DONE: u32 = 1 << 1;
const FAILED: u32 = 1 << 2;

static FLAGS: AtomicU32 = AtomicU32::new(0);

fn set_flag(bit: u32) -> bool {
    // fetch_or: sets the bit and returns the value before the call
    let before = FLAGS.fetch_or(bit, Ordering::SeqCst);
    before & bit == 0 // true when this call set the bit first
}

fn main() {
    println!("ready first: {}", set_flag(READY));
    println!("ready again: {}", set_flag(READY));
    set_flag(DONE);
    set_flag(FAILED);
    let all = FLAGS.load(Ordering::SeqCst);
    println!("all flags: {all:#010b}");
    println!("done set: {}", all & DONE != 0);
}

How it works

fetch_or Sets Atomic Bit Flags is built around the functions set_flag and main.

Caveats

  • Runs on the standard library alone; nothing to install.

Putting it to use

The primary signature is fn set_flag(bit: u32) -> bool

Expect labeled output — ready first:, ready again:, all flags: — when the file runs.

The entry point wires set_flag together — run it once and the whole demo flows.

The core lines of the flow

fn set_flag(bit: u32) -> bool {
    // fetch_or: sets the bit and returns the value before the call
    let before = FLAGS.fetch_or(bit, Ordering::SeqCst);
    before & bit == 0 // true when this call set the bit first
}

Interactive Tools for This Topic

FAQ

What does fetch_or Sets Atomic Bit Flags print when run?
Execute the whole file; each printed line is prefixed with a label like `ready first:`, `ready again:`, `all flags:`.