docs

#2.19. par:并行处理 API

本页内容

core::par 模块提供数据并行 API。它的设计借鉴了 Rust 的 Rayon,并与 task::* 运行在同一个工作窃取调度器上。

模块 par 在 prelude 中,所以无需导入即可使用 par::for_each、par::map 等;模块前缀 par:: 仍然保留。需要让并行意图一目了然时,推荐显式写出 use core::par::*;。

#2.19.1. 核心 API

核心 API 由七个函数组成;try_scope(2.19.3)是第八个。

nabi
fn for_each<I: IntoIterator<Item = T>, T: Send>(iter: I, f: fn(T) + Send + Sync);
fn map<I: IntoIterator<Item = T>, T: Send, U: Send>(iter: I, f: fn(T) -> U + Send + Sync) -> List<U>;
fn fold<I: IntoIterator<Item = T>, T: Send>(iter: I, init: T, f: fn(T, T) -> T + Send + Sync) -> T;
fn reduce<I: IntoIterator<Item = T>, T: Send>(iter: I, f: fn(T, T) -> T + Send + Sync) -> T | none;
fn filter<I: IntoIterator<Item = T>, T: Send>(iter: I, pred: fn(T) -> bool + Send + Sync) -> List<T>;
fn join<T1: Send, T2: Send>(f1: fn() -> T1 + Send, f2: fn() -> T2 + Send) -> (T1, T2);    // 2 in parallel
fn scope(f: fn(Scope));                                          // dynamic spawn

所有接受元素的函数都接受任意 IntoIterator。它们共用一组约束:元素是 T: Send;for_each / map / fold / reduce / filter 的 f 会被多个工作线程同时调用,所以它是 + Send + Sync。

  • map / filter 的结果 List 与输入顺序相同。for_each 在多个工作线程上同时调用 f,所以调用顺序未指定。
  • for_each / map / filter / fold / reduce 把每个元素交给一个工作线程。两个元素不得到达同一个不是 Sync 的集合(2.13.9)。每次调用都先查找是否有从两个元素都能到达的集合:像交接复制那样,沿着元素的各个部分及其集合的元素向下追踪到任意深度,但不进入普通值(数字、bool、str)的集合。如果找到,元素会在调用线程上依次运行,从而不会产生竞争,原地修改的效果与使用工作线程时相同,并且会有一条警告指出调用位置(每个位置一次)。切片只读:元素可以通过列表的切片共享该列表(一个大列表的分块),只要没有元素持有列表本身;切片所到达的元素会逐个追踪。可写视图(SliceMut,来自 chunks_mut 或 split_at_mut)也可以共享列表:检查会记录每个元素的视图和切片覆盖列表的哪一部分;当一个元素写入的部分与另一个元素读或写的部分重叠,或另一个元素持有整个列表时,这些元素逐个运行。因此 par::for_each(xs.chunks_mut(n), f) 会原地写入列表,每个工作线程写自己的部分,多个列表的视图也可以合并(zip)成一个元素(pos.chunks_mut(n).zip(vel.chunks(n)))。如果视图创建之后其列表改变过大小(过期,2.9.7a),会在任何元素运行之前触发 panic。检查会在对象头中标记元素到达的每个集合(单列表元素每个集合约 15 ns,嵌套元素每个集合约 50 ns,主要是内存读取;没有集合的元素没有开销):对于每个工作量很小的大量小元素,这一开销可能超过工作本身。警告会说明应当改写成什么:让每个元素持有自己的值(存入前先对共享值 .clone()),把元素只读的数据冻结(xs.freeze(),2.9.7b),或通过检查不会追踪的其他 Sync 类型共享,或者用 chunks_mut 拆分列表。元素中的 future 按其帧计算:持有同一个 future 的两个元素也会逐个运行。par 不交出它的元素,所以帧中捕获了集合的 future 不能作为元素(编译错误):应当把这样的 future 作为任务启动(2.18.1)。filter 的结果与输入共享元素。
  • fold 把输入分成若干块,并行地折叠每一块,然后按顺序折叠 init 和各块的结果。输入为空时返回 init。reduce 做同样的事但没有 init,与 Iterator::reduce 一样:输入为空时返回 none(2.19.4)。
  • 在 scope 中启动的子任务会在作用域结束时全部被 join。
  • par 与任务运行在同一个工作窃取线程池上(2.18.3)。在 par 中等待的工作线程在此期间会运行其他任务,所以在任务内调用 par 不会死锁。传给 scope 的 Scope 及其句柄如下:
nabi
struct Scope { /* list of jobs in the scope */ }
impl Scope {
    fn spawn<T: Send>(self, f: fn() -> T + Send) -> ScopeHandle<T>;
}

struct ScopeHandle<T> { /* one spawned job */ }
impl<T> ScopeHandle<T> {
    fn join(self) -> T;          // waits until that job finishes
}

scope 结束时也会等待所有没有被 join 的作业。

nabi
par::scope(|s| {
    let left = s.spawn(|| sum_range(0, 500));
    let right = s.spawn(|| sum_range(500, 1000));
    println(f"{left.join() + right.join()}");   // join waits for that job
    s.spawn(|| log("background"));                    // not joined; the scope waits for it at its end
});

#示例

nabi
use core::par::*;

let xs: List<i32> = (0..1000).collect();

par::for_each(xs, |x| { process(x) });

let squared: List<i32> = par::map(xs, |x| x * x);

let total: i32 = par::fold(squared, 0, |a, b| a + b);

let (a, b) = par::join(
    || compute_a(),
    || compute_b(),
);

par::scope(|s| {
    for chunk in chunks {
        s.spawn(|| process_chunk(chunk));
    }
});           // ← every spawn is guaranteed complete at the end of the scope

#对列表的并行循环

这些函数接受任意 IntoIterator,所以对大列表的并行循环以其分块作为元素来写:每个工作线程得到列表的一部分,而不是一次一个元素。由多个工作线程运行的闭包不能捕获列表(它不是 Sync);但可以捕获冻结的列表。

nabi
// Read: the sum of 100M numbers, one chunk per item.
let parts = par::map(xs.chunks(1 << 16), |c| { let s = 0.0; for x in c { s += x; } s });
let total = parts.iter().sum();

// Write in place: each worker updates its own part.
par::for_each(xs.chunks_mut(1 << 16), |c| { for i in 0..c.len() { c[i] = c[i] * 2.0; } });

// Several lists of one length (an ECS system): zip their parts.
let items = pos.chunks_mut(4096).zip(vel.chunks(4096));
par::for_each(items, |(p, v)| { for i in 0..p.len() { p[i] = p[i] + v[i] * dt; } });

// Read-only data every item looks up: freeze it and capture it.
let table = table.freeze();
let out = par::map(queries, |q| table[q.slot]);

#2.19.2. par::for_each 与 Iterator

顺序处理与并行处理通过调用形式区分。

nabi
xs.into_iter().for_each(f);     // sequential (single thread)
par::for_each(xs, f);            // parallel (worker pool)

工作按块以数据并行方式分配,工作窃取调度器会自动平衡不均衡的工作负载。

#2.19.3. par::scope:结构化并行

par::scope 是可以动态启动工作的结构化并行 API。

nabi
par::scope(|s| {
    let h1 = s.spawn(|| task1());
    let h2 = s.spawn(|| task2());
    // results of h1, h2 are usable (inside the scope)
    // joined automatically at the end of the scope
});

这遵循结构化并发的形式:作用域会一直阻塞,直到每个子 spawn 都完成。保留到其 par::scope 之后的 Scope 不能再启动工作:spawn 会触发 panic,消息为 Scope::spawn: the scope has ended; call spawninside the closure passed topar::scope``。

#par::try_scope:遇到第一个错误即取消

对于会抛出错误的子任务,使用 try_scope。

nabi
fn try_scope<E: Send>(f: fn(TryScope<E>) throws (E)) throws (E);

impl<E: Send> TryScope<E> {
    fn spawn<T: Send>(self, f: fn() throws (E) -> T + Send) -> TryScopeHandle<T, E>;
    fn is_cancelled(self) -> bool;
}

impl<T, E: Send> TryScopeHandle<T, E> {
    fn join(self) throws (E) -> T;     // its own error, or the scope's first error if cancelled before starting
}

如果某个子任务或函数体 f 本身抛出错误,作用域就被取消。尚未开始的子任务不再运行,已经在运行的子任务运行到完成。所有子任务结束后,try_scope 重新抛出第一个错误(来自 f 的错误会被捕获,取消作用域,并以同样方式重新抛出)。正在运行的子任务可以检查 is_cancelled() 以提前结束。

nabi
try par::try_scope(|s: par::TryScope<IoError>| {
    let a = s.spawn(|| try load("a"));
    let b = s.spawn(|| try load("b"));
    use_both(try a.join(), try b.join());
});

#2.19.4. par::fold:要求结合律

par::fold 和 par::reduce 的签名如下;使用它们需要满足一些数学条件。

nabi
fn fold<I: IntoIterator<Item = T>, T: Send>(iter: I, init: T, f: fn(T, T) -> T + Send + Sync) -> T;
fn reduce<I: IntoIterator<Item = T>, T: Send>(iter: I, f: fn(T, T) -> T + Send + Sync) -> T | none;

合并函数 f 必须满足结合律,结果才是确定的。reduce 不接受 init,没有元素时返回 none。init 最好是单位元:+ 为 0,* 为 1。对于不满足结合律的函数,例如累加大数值的浮点求和,结果可能不确定,需要特别注意。

nabi
let sum: i64 = par::fold(1..6, 0, |a, b| a + b);    //→ 15

// floating-point: the result may differ slightly
let total: f64 = par::fold(values, 0.0, |a, b| a + b);

let max: i64 | none = par::reduce(scores, |a, b| a.max(b));   // none if scores is empty

#2.19.5. par::join:恰好两个

要并发运行两个作业并得到两个结果,使用 par::join。

nabi
let (a, b) = par::join(
    || expensive_computation_1(),
    || expensive_computation_2(),
);

两个作业是最常见的 fork-join 形式,所以提供了专门的函数。对于 N 个作业,使用 par::for_each 或 par::scope。

#2.19.6. SIMD / GPU 集成

par 模块以 CPU 数据并行为中心:par::map 对每个元素调用一次 f,自身不做 SIMD 多版本化(f 的代码与其他代码一样,按构建的 --target 及其基线 CPU 编译,0.6.4)。GPU 加速不属于标准库;库将通过计划在后续版本中提供的后端接口使用它。

nabi
par::map(xs, |x| heavy_op(x));     // CPU work-stealing

#2.19.7. 模块映射

各 API 所在模块及内部策略:

项模块策略
par::for_eachcore::par分块 + 工作窃取
par::mapcore::par并行收集
par::foldcore::par树形归约
par::reducecore::par树形归约,无 init
par::filtercore::par并行判定,然后按顺序收集
par::joincore::par双任务工作窃取
par::scopecore::parspawn 句柄 + 自动 join
par::try_scopecore::parspawn 句柄 + 自动 join,遇到第一个错误即取消

在内部,它是 task::spawn 之上的一层,共用同一个调度器。

发现错误? 在 GitHub 上编辑此页 最后更新: