Lyricdev
GitHub

std.thread

Threads and pools of them: Thread, Pool and parallelMap.

Each thread runs a scheduler of its own from std.task; a task never moves to another thread. Threads run at the same time: what they share, they share through a channel, an atomic or a lock — anything else is a data race.

Examples

import std.io { println };
import std.thread { parallelMap };

fn main(): void throws Error {
    let squares = try parallelMap([1, 2, 3, 4], (n) => n * n);
    println(squares.iter().join(" "));
}
1 4 9 16

Types

Thread class — An operating-system thread with a scheduler of its own.
Pool class — A fixed set of threads that run the tasks given to the pool.

Functions

pub fn parallelMap<T, U, E :: [Error]>(
    xs: Slice<T>,
    f: fn(T) -> U throws E
): U[] throws [E, Cancelled]

Calls f on every element of xs on several threads and returns the results in the elements' order.

The program's pool does the work — a thread for each processor, started at the first call and there until the program ends — in pieces, four for each thread; the first element's call runs on the caller's thread. f runs on other threads: what it shares, it shares through a channel, an atomic or a lock.

Errors

Where calls throw, the error of the first element, in order, whose call throws comes out once every piece has ended; a piece stops at its first error, so a later element of that piece may go uncalled. An error from the first element's call comes out at once. A cancelled caller cancels the pieces and throws Cancelled.