我试图考虑如何从不同的线程将东西插入到hasmap中,但仍然无法实现.
为什么下面的程序在每次执行时都缺少一些键?
我目前的理解是,.write
等待获取锁,.join
等待所有线程完成?
因此,我希望最终所有线程都将它们的值插入到哈希图中,但显然我仍然遗漏了一些东西.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::RwLock;
use std::thread;
use std::vec;
pub fn main() {
let mut contacts: HashMap<String, String> = HashMap::new();
contacts.insert("main-thread".to_owned(), "hello world".to_owned());
let contacts = Arc::new(RwLock::new(contacts));
let mut children = vec![];
for _ in 0..10 {
let lock_contacts = Arc::clone(&contacts);
children.push(thread::spawn(move || {
let num = thread::current().id();
let num = format!("{num:?}");
if let Ok(mut contacts) = lock_contacts.write() {
contacts.insert(num.clone(), "hey".to_owned());
}
}));
}
let _ = children.into_iter().map(|c| c.join());
dbg!(contacts);
}