无法迭代 Arc Mutex
Unable to iterate over Arc Mutex
考虑以下代码,我将每个线程附加到一个 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");
}
}
首先,您不需要 threads
包含在 Mutex
中的 Arc
中。你可以只保留 Vec
:
let mut threads = Vec::new();
...
threads.push(handle);
之所以如此,是因为您不会在线程之间共享 threads
。您只能从主线程访问它。
其次,如果出于某种原因您确实需要将其保留在Arc
中(例如,如果您的示例没有反映程序的实际结构,这更complex),那么你需要锁定互斥体以获得对包含向量的引用,就像你在推送时所做的那样:
for t in threads.lock().unwrap().iter() {
...
}
考虑以下代码,我将每个线程附加到一个 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");
}
}
首先,您不需要 threads
包含在 Mutex
中的 Arc
中。你可以只保留 Vec
:
let mut threads = Vec::new();
...
threads.push(handle);
之所以如此,是因为您不会在线程之间共享 threads
。您只能从主线程访问它。
其次,如果出于某种原因您确实需要将其保留在Arc
中(例如,如果您的示例没有反映程序的实际结构,这更complex),那么你需要锁定互斥体以获得对包含向量的引用,就像你在推送时所做的那样:
for t in threads.lock().unwrap().iter() {
...
}