2015-06-01 30 views
2

請考慮下面的代碼,我將每個線程追加到Vector以便在我產生每個線程後將它們連接到主線程,但是我無法在我的電話上調用iter() JoinHandlers矢量。無法遍歷Arc Mutex

我該如何去做這件事?

fn main() { 
    let requests = Arc::new(Mutex::new(Vec::new())); 
    let threads = Arc::new(Mutex::new(Vec::new())); 

    for _x in 0..100 { 
     println!("Spawning thread: {}", _x); 

     let mut client = Client::new(); 
     let thread_items = requests.clone(); 

     let handle = thread::spawn(move || { 
      for _y in 0..100 { 
       println!("Firing requests: {}", _y); 

       let start = time::precise_time_s(); 

       let _res = client.get("http://jacob.uk.com") 
        .header(Connection::close()) 
        .send().unwrap(); 

       let end = time::precise_time_s(); 

       thread_items.lock().unwrap().push((Request::new(end-start))); 
      } 
     }); 

     threads.lock().unwrap().push((handle)); 
    } 

    // src/main.rs:53:22: 53:30 error: type `alloc::arc::Arc<std::sync::mutex::Mutex<collections::vec::Vec<std::thread::JoinHandle<()>>>>` does not implement any method in scope named `unwrap` 
    for t in threads.iter(){ 
     println!("Hello World"); 
    } 
} 
+1

請提供[MCVE](http://stackoverflow.com/help/mcve)。您的代碼缺少關於您正在使用哪些庫的所有解釋,並且包含與您的問題無關的信息。 –

回答

8

首先,你不需要threadsMutex包含在Arc。你可以把它只是Vec

let mut threads = Vec::new(); 
... 
threads.push(handle); 

這是因爲你不同意,這個數字遠,線程threads。您只能從主線程訪問它。

其次,如果由於某種原因,你需要保持它在Arc(例如,如果你的例子並不反映你的程序,它是更爲複雜的實際結構),那麼你就需要鎖定互斥獲得參考包含的向量,就像您在推送時一樣:

for t in threads.lock().unwrap().iter() { 
    ... 
}