2015-06-01 32 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() { 
    ... 
}