我有一个循环处理 HTTP 响应的程序。这些不依赖于彼此,所以它们可以同时完成。我正在使用线程来执行此操作:
extern crate hyper;
use std::thread;
use std::sync::Arc;
use hyper::Client;
fn main() {
let client = Arc::new(Client::new());
for num in 0..10 {
let client_helper = client.clone();
thread::spawn(move || {
client_helper.get(&format!("http://example.com/{}", num))
.send().unwrap();
}).join().unwrap();
}
}
这行得通,但我可以看到这样做的其他可能性,例如:
let mut threads = vec![];
threads.push(thread::spawn(move || {
/* snip */
for thread in threads {
let _ = thread.join();
}
使用返回线程处理程序的函数对我来说也很有意义,但我不知道该怎么做……不确定返回类型必须是什么。
在 Rust 中等待并发线程的最佳/推荐方式是什么?
最佳答案
您的第一个程序实际上没有任何并行性。每次启动一个工作线程时,您都会立即等待它完成,然后再启动下一个线程。当然,这比没用还糟糕。
第二种方式可行,但有些箱子可以为您完成一些繁琐的工作。例如,scoped_threadpool
和 crossbeam
有线程池,允许你写类似的东西(未经测试,可能包含错误):
let client = &Client::new();// No Arc needed
run_in_pool(|scope| {
for num in 0..10 {
scope.spawn(move || {
client.get(&format!("http://example.com/{}", num)).send().unwrap();
}
}
})
关于multithreading - 等待并发线程的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35670401/