multithreading - 等待并发线程的首选方法

标签 multithreading rust

我有一个循环处理 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_threadpoolcrossbeam有线程池,允许你写类似的东西(未经测试,可能包含错误):

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/

相关文章:

c++ - 为什么 cv::mat 的 vector 总是返回第一张图像?

c# - 如何重新创建 "Index was outside the bounds of the array"添加项目到字典?

c++多线程单例 - 此代码有任何问题

iphone - 使用调度队列进行 Google 地理编码的效率 - 如何改进 - iPhone

rust - 使用生命周期参数为特征分离可变借位

c++ - 使用 pthread_cond_wait 等待的线程在收到信号后需要多长时间才能唤醒?我如何估计这个时间?

rust - 无法移出 `[Foo;2]` 类型,一个非复制数组

rust - 从 `&PathBuf` 转换为 `PathBuf`

python - 执行从 Rust/Python 源代码生成的 LLVM IR 代码

Rust 导入错误