实现说明
活动部件是函数 setup、main。
迭代发生在 for id in 0..3 内部——循环之外的语句只执行一遍。
使用要点
- 演示输出是带标签的(
thread、setup ran),每个操作都会留下自己的一行标注。
常见问题
运行「std::sync::Once 一次性初始化」会打印什么?
整个文件跑完,输出行以 thread、setup ran 这类前缀开头。
入口签名:fn setup()
核心语句
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();
代码示例
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));
}