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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.