And*_*row 2 multithreading rust
我有一个哈希:
let mut hash: HashMap<String, Vec<i32>> = HashMap::new();
Run Code Online (Sandbox Code Playgroud)
我开始一个主题:
thread::spawn(move || delete_from(&mut hash));
fn delete_from(m: &mut HashMap<String, Vec<i32>>) {
loop {
m.remove(a_key)
}
}
Run Code Online (Sandbox Code Playgroud)
这很棒.我sleep在那里有一个声明(未显示),它正确地a_key从中删除它HashMap.当我打印出来时,我可以看到线程慢慢移除每个项目.
我想开始第二个帖子:
thread::spawn(move || insert_into(&mut hash));
fn insert_into(m: &mut HashMap<String, Vec<i32>>) {
loop {
m.insert(a_string, a_vector);
}
}
Run Code Online (Sandbox Code Playgroud)
插入.但是当我添加第二个线程时,我得到:
捕获移动值:
hash[E0382]
设置它的正确方法是什么?
实际上,hashmap被移动到第一个线程中,因此没有其他线程可以访问它.您需要一个Arc共享所有权,以便多个线程可以访问地图,以及Mutex同步,以便他们不会同时尝试修改地图.
这是什么样子:
use std::sync::{Arc, Mutex};
let hash: Arc<Mutex<HashMap<String, Vec<i32>>>> = Arc::new(Mutex::new(HashMap::new())); // initialize the map within an Arc (for sharing) and a Mutex (for synchronization)
let clone1 = hash.clone(); // clone the Arc so it can be owned jointly by multiple threads
let clone2 = hash.clone(); // clone the Arc so it can be owned jointly by multiple threads
thread::spawn(move || delete_from(&clone1));
thread::spawn(move || insert_into(&clone2));
fn delete_from(m: &Mutex<HashMap<String, Vec<i32>>>) {
loop {
m.lock().unwrap().remove(a_key); // lock the mutex, remove a value, unlock
}
}
fn insert_into(m: &Mutex<HashMap<String, Vec<i32>>>) {
loop {
m.lock().unwrap().insert(a_string, a_vector); // lock the mutex, insert a value, unlock
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
221 次 |
| 最近记录: |