2016-08-19 66 views
1

我有一個哈希:如何讓一個從HashMap中刪除的線程和另一個插入的線程?

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中刪除它。打印出來時,我可以看到線程慢慢地移除每個項目。

我要開始第2個線程:

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

回答

6

因爲它是散列圖移動到第一個線程,所以沒有其他線程可以訪問它。您需要共享所有權的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 
    } 
} 
+0

啊,謝謝U,我現在終於明白生鏽。這是我失蹤的最後一個信息。 –