如何从HashMap中删除一个线程并插入另一个线程?

时间:2016-08-19 18:30:07

标签: multithreading rust

我有一个哈希:

let mut hash: HashMap<String, Vec<i32>> = HashMap::new();

我开始一个主题:

thread::spawn(move || delete_from(&mut hash));

fn delete_from(m: &mut HashMap<String, Vec<i32>>) {
    loop {
        m.remove(a_key)
    }
}

这很有效。我在那里有一个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);
    }
}

即插入。但是当我添加第二个线程时,我得到了:

  

捕获移动的值:hash [E0382]

设置它的正确方法是什么?

The complete code

1 个答案:

答案 0 :(得分:6)

实际上,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
    }
}
相关问题