One Time Setup With std::sync::Once

Run a setup function exactly once across threads with std::sync::Once and call_once, then read the side effects from shared state.

RustConfig Management

Code

rustsnippet
26 lines
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, Once};

static INIT: Once = Once::new();
static CALLS: AtomicU32 = AtomicU32::new(0);
static REGISTRY: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());

fn setup() {
    CALLS.fetch_add(1, Ordering::SeqCst);
    REGISTRY.lock().unwrap().push("metrics");
}

fn main() {
    let mut handles = Vec::new();
    for id in 0..3 {
        handles.push(std::thread::spawn(move || {
            // 无论多少线程同时调用,setup 只执行一次
            INIT.call_once(setup);
            println!("thread {id} sees registry ready");
        }));
    }
    for handle in handles {
        handle.join().unwrap();
    }
    println!("setup ran {} time(s)", CALLS.load(Ordering::SeqCst));
}

How the snippet works

Everything happens inside the functions setup and main.

One loop does the cycling here: for id in 0..3.

Watch out for

  • Entirely standard-library — copy it in and it runs.

Using it

Entry signature: fn setup()

The demo output is labeled (thread, setup ran), so every printed line maps back to its originating operation.

Key statements

REGISTRY.lock().unwrap().push("metrics");
handles.push(std::thread::spawn(move || {
// 无论多少线程同时调用,setup 只执行一次
INIT.call_once(setup);
println!("thread {id} sees registry ready");
}));
handle.join().unwrap();

Interactive Tools for This Topic

FAQ

What does One Time Setup With std::sync::Once print when run?
Invoke the file as-is — the `thread`, `setup ran` prefixes identify which step printed each line.