docs

#2.19. par - Parallel processing API

On this page

The core::par module provides a data-parallel API. Its design is inspired by Rust's Rayon, and it runs on the same work-stealing scheduler as task::*.

The module par is in the prelude, so par::for_each, par::map and the rest are usable without any import; the module prefix par:: is still kept. Where the parallel intent should be visibly clear, writing use core::par::*; explicitly is recommended.

#2.19.1. Core API

The core API consists of seven functions; try_scope (2.19.3) is the eighth.

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

Every one that takes items takes any IntoIterator. They share one bound set: the items are T: Send, and the f of for_each / map / fold / reduce / filter is called by several workers at once, so it is + Send + Sync.

  • The result List of map / filter is in the same order as the input. for_each calls f on several workers at once, so the order of its calls is unspecified.
  • for_each / map / filter / fold / reduce give each item to a worker. Two items must not reach one collection that is not Sync (2.13.9). Each call first looks for a collection reached from two items, following the items' parts and the elements of their collections to any depth, as a hand-off copy does, but not into collections of plain values (numbers, bool, str): if it finds one, the items run one after another on the calling thread, so nothing races and in-place changes stay as with workers, and a warning names the call site (once per site). Slices only read: items may share a list through slices of it (chunks of one big list), as long as no item holds the list itself; the elements a slice reaches are followed one by one. Writable views (SliceMut, from chunks_mut or split_at_mut) may share a list too: the check notes the part of the list each item's views and slices cover, and the items run one at a time when a part one item writes overlaps a part another item reads or writes, or another item holds the whole list. So par::for_each(xs.chunks_mut(n), f) writes the list in place, each worker its own part, and the views of several lists zip into one item (pos.chunks_mut(n).zip(vel.chunks(n))). A view whose list was resized since it was made (stale, 2.9.7a) panics before any item runs. The check marks each collection the items reach in the object's header (about 15 ns per collection for one-list items and about 50 ns per collection on nested items, mostly the memory reads; items with no collection cost nothing): for many small items with little work each it can exceed the work. The warning says what to write instead: give each item its own values (.clone() a shared one before storing it), freeze what the items only read (xs.freeze(), 2.9.7b) or share it through another Sync type, which the check does not follow, or split a list with chunks_mut. A future among the items counts as its frame: two items holding one future run one at a time too. par does not hand its items over, so a future whose frame captures a collection cannot be an item (a compile error): spawn such futures as tasks instead (2.18.1). The result of filter shares the input's items.
  • fold splits the input into chunks, folds each chunk in parallel, then folds init and the chunk results in order. If the input is empty it returns init. reduce does the same with no init, as Iterator::reduce: none if the input is empty (2.19.4).
  • Children spawned inside a scope are all joined when the scope ends.
  • par runs on the same work-stealing pool as tasks (2.18.3). A worker waiting inside par runs other tasks meanwhile, so calling par inside a task does not deadlock. The Scope passed to scope and its handle are:
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
}

When scope ends it also waits for every job that was not joined.

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
});

#Example

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

#Parallel loops over a list

The functions take any IntoIterator, so a parallel loop over a big list is written with its chunks as the items: each worker gets a part of the list, not one element at a time. A closure several workers run cannot capture a list (it is not Sync); a frozen list it can.

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 vs Iterator

Sequential and parallel processing are distinguished by the form of the call.

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

Work is distributed data-parallel in chunks, and the work-stealing scheduler automatically balances unbalanced workloads.

#2.19.3. par::scope - structured parallelism

par::scope is a structured parallel API that can spawn work dynamically.

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
});

This follows the structured concurrency form: the scope blocks until every child spawn has completed. A Scope kept past its par::scope cannot spawn: spawn panics with Scope::spawn: the scope has ended; call spawninside the closure passed topar::scope``.

#par::try_scope - cancel on the first error

For children that throw errors, use 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
}

If one child, or the body f itself, throws, the scope is cancelled. Children not yet started are not run, and children already running run to completion. When all children have finished, try_scope rethrows that first error (an error from f is caught, cancels the scope and is rethrown the same way). A running child can check is_cancelled() to finish early.

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 - associativity required

The signatures of par::fold and par::reduce are as follows; using them involves some mathematical conditions.

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;

The combining function f must be associative for the result to be deterministic. reduce takes no init and returns none for no items. init should preferably be the identity: 0 for +, 1 for *. For a non-associative function, such as floating-point summation accumulating large values, the result may be nondeterministic and needs explicit care.

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 - exactly two

Use par::join to run two jobs concurrently and receive the pair of results.

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

Two jobs are the most common fork-join form, so a dedicated function is provided. For N jobs, use par::for_each or par::scope.

#2.19.6. SIMD / GPU integration

The par module centers on CPU data parallelism: par::map calls f once per item and applies no SIMD multiversioning of its own (the code of f is compiled for the build's --target and its baseline CPU like any other code, 0.6.4). GPU acceleration is not part of the standard libraries; libraries will reach it through the backend interface, planned for a later release.

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

#2.19.7. Module mapping

The module location and internal strategy of each API:

ItemModuleStrategy
par::for_eachcore::parchunk + work-steal
par::mapcore::parparallel collect
par::foldcore::partree reduction
par::reducecore::partree reduction, no init
par::filtercore::parparallel predicate, then in-order collect
par::joincore::par2-task work-steal
par::scopecore::parspawn handle + auto-join
par::try_scopecore::parspawn handle + auto-join, cancel on the first error

Internally it is one layer on top of task::spawn, sharing the same scheduler.

Found a mistake? Edit this page on GitHub. Last updated