使用 std::sync::Mutex
可以多线程共享可变数据,Mutex
、RwLock
和原子类型,即使声明为 non-mut
,这些类型也可以修改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| use std::borrow::Cow; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration;
fn main() { let metrics: Arc<Mutex<HashMap<Cow<'static, str>, usize>>> = Arc::new(Mutex::new(HashMap::new())); for _ in 0..32 { let m = metrics.clone(); thread::spawn(move || { let mut g = m.lock().unwrap();
let data = &mut *g;
let value = data.entry("hello".into()).or_insert(0); *value += 1;
}); }
thread::sleep(Duration::from_millis(100)); println!("metrics: {:?}", metrics.lock().unwrap()); }
|