为什么使用Iterator :: map生成线程不能并行运行线程?

时间:2019-04-03 08:50:09

标签: multithreading functional-programming rust

我在Rust中编写了一个简单的多线程应用程序,将数字从1加到x。 (我知道有一个公式可以解决这个问题,但关键是要在Rust中编写一些多线程代码,而不是得到结果。) 它工作正常,但是在我将其重构为更具功能性的样式而不是命令式之后,多线程处理不再加速。在检查CPU使用率时,看来我的4核心/ 8线程CPU中仅使用了一个核心。原始代码具有790%的CPU使用率,而重构版本只有99%的CPU使用率。

原始代码:

use std::thread;

fn main() {
    let mut handles: Vec<thread::JoinHandle<u64>> = Vec::with_capacity(8);

    const thread_count: u64 = 8;
    const batch_size: u64 = 20000000;

    for thread_id in 0..thread_count {
        handles.push(thread::spawn(move || {
            let mut sum = 0_u64;

            for i in thread_id * batch_size + 1_u64..(thread_id + 1) * batch_size + 1_u64 {
                sum += i;
            }

            sum
        }));
    }

    let mut total_sum = 0_u64;

    for handle in handles.into_iter() {
        total_sum += handle.join().unwrap();
    }
    println!("{}", total_sum);
}

重构代码:

use std::thread;

fn main() {
    const THREAD_COUNT: u64 = 8;
    const BATCH_SIZE: u64 = 20000000;

    // spawn threads that calculate a part of the sum
    let handles = (0..THREAD_COUNT).map(|thread_id| {
        thread::spawn(move ||
            // calculate the sum of all numbers from assigned to this thread
            (thread_id * BATCH_SIZE + 1 .. (thread_id + 1) * BATCH_SIZE + 1)
                .fold(0_u64,|sum, number| sum + number))
    });

    // add the parts of the sum together to get the total sum
    let sum = handles.fold(0_u64, |sum, handle| sum + handle.join().unwrap());

    println!("{}", sum);
}
程序的输出是相同的(12800000080000000),但是重构的版本要慢5-6倍。

似乎迭代器是延迟计算的。如何强制评估整个迭代器?我试图将其收集到类型为[thread::JoinHandle<u64>; THREAD_COUNT as usize]的数组中,但是随后出现以下错误:

  --> src/main.rs:14:7
   |
14 |     ).collect::<[thread::JoinHandle<u64>; THREAD_COUNT as usize]>();
   |       ^^^^^^^ a collection of type `[std::thread::JoinHandle<u64>; 8]` cannot be built from `std::iter::Iterator<Item=std::thread::JoinHandle<u64>>`
   |
   = help: the trait `std::iter::FromIterator<std::thread::JoinHandle<u64>>` is not implemented for `[std::thread::JoinHandle<u64>; 8]`

将向量收集起来确实可行,但是这似乎是一个怪异的解决方案,因为预先知道大小。有没有比使用向量更好的方法了?

1 个答案:

答案 0 :(得分:4)

Rust中的迭代器是惰性的,因此直到handles.fold尝试访问迭代器的相应元素之前,您的线程才启动。基本上会发生什么:

  1. handles.fold尝试访问迭代器的第一个元素。
  2. 第一个线程已启动。
  3. handles.fold调用其关闭,第一个线程调用handle.join()
  4. handle.join等待第一个线程完成。
  5. handles.fold尝试访问迭代器的第二个元素。
  6. 第二个线程已启动。
  7. 等等。

在折叠结果之前,应将手柄收集到向量中:

let handles: Vec<_> = (0..THREAD_COUNT)
    .map(|thread_id| {
        thread::spawn(move ||
            // calculate the sum of all numbers from assigned to this thread
            (thread_id * BATCH_SIZE + 1 .. (thread_id + 1) * BATCH_SIZE + 1)
                .fold(0_u64,|sum, number| sum + number))
    })
    .collect();

或者您也可以使用像Rayon这样的板条箱,它提供并行的迭代器。