Initialize Global Config Once with OnceLock
Initialize process-wide configuration exactly once across threads with std::sync::OnceLock, then read it without locks or clones.
Code
use std::sync::{Arc, Barrier, OnceLock};
use std::thread;
#[derive(Debug, Clone)]
struct Config {
service: String,
workers: usize,
debug: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
service: "orders".to_string(),
workers: 4,
debug: false,
}
}
}
static CONFIG: OnceLock<Config> = OnceLock::new();
fn config() -> &'static Config {
CONFIG.get_or_init(|| {
println!("loading configuration once");
Config::default()
})
}
fn main() {
let barrier = Arc::new(Barrier::new(4));
let mut handles = Vec::new();
for worker in 0..4 {
let barrier = Arc::clone(&barrier);
handles.push(thread::spawn(move || {
barrier.wait();
let current = config();
println!(
"worker {worker}: {} ({} workers)",
current.service, current.workers
);
current.workers
}));
}
let total: usize = handles
.into_iter()
.map(|handle| handle.join().expect("worker panicked"))
.sum();
println!("total workers: {total}");
println!("same instance: {}", std::ptr::eq(config(), config()));
}
How it works
The working surface is the functions default, config and main — everything else is wiring.
The file repeats itself only inside for worker in 0..4.
Putting it to use
The primary signature is fn default() -> Self
The demo output is labeled (loading configuration once, worker, total workers:), so every printed line maps back to its originating operation.
The sequence config lives in main; running the file triggers it.
Core lines
handles.push(thread::spawn(move || {
barrier.wait();
let current = config();
println!(
"worker {worker}: {} ({} workers)",
current.service, current.workers
);
current.workers
}));
fn config() -> &'static Config {
CONFIG.get_or_init(|| {
println!("loading configuration once");
Config::default()
})
}
impl Default for Config {
fn default() -> Self {
Self {
service: "orders".to_string(),
workers: 4,
debug: false,
}
}
}
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.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Initialize Global Config Once with OnceLock print when run?
- Running the file directly is enough — expect labeled output lines such as `loading configuration once`, `worker`, `total workers:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.