Jac*_*ark 2 multithreading asynchronous rust
考虑下面的代码,我将每个线程附加到Vector,以便在我生成每个线程之后将它们连接到主线程,但是我无法调用iter()
JoinHandlers的向量.
我该怎么做呢?
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");
}
}
Run Code Online (Sandbox Code Playgroud)
首先,你不需要threads
被包含在Arc
在Mutex
.你可以保持它Vec
:
let mut threads = Vec::new();
...
threads.push(handle);
Run Code Online (Sandbox Code Playgroud)
这是因为你没有threads
在线程之间共享.您只能从主线程访问它.
其次,如果由于某种原因,你就需要保持它Arc
(例如,如果你的例子并不反映你的程序,它是更为复杂的实际结构),那么你就需要锁定互斥获取到包含向量的参考,只是就像你推动时一样:
for t in threads.lock().unwrap().iter() {
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
832 次 |
最近记录: |