LEVIATHAN vd52e79c4 · d52e79c486

Library

Threads, workers and message passing

Run work in parallel with std::spawn; values cross between threads by copy, and Channel is the way to talk to a running worker.

since 0.1.0-alpha.1linux

Description

A worker is a piece of work that runs on another thread of execution. The model is isolation with copying: a worker captures its inputs by copy, runs, and returns a result, and every value that crosses a thread boundary is deep-copied. No two threads ever share the same object, so there are no data races and no locks to write.

  • std::spawn(body) starts a worker. body is a closure with no parameters, and spawn returns a Worker<T> where T is the closure's result type.
  • A Worker<T> is a Promise<T>, so await worker is the join: it waits for the result and rethrows the body's exception, class preserved, if it threw. There is no second way to wait.
  • The variables the closure captures are snapshotted at the spawn call. Changing the original afterwards is not seen by the worker, and changes the worker makes to its copy do not reach the original. Writing a captured local itself in the closure (n += 1, xs.add(1)) is a compile error, as in any lambda (lang.primary-expressions); copy it into a local of the closure, or return the result.
  • Channel<T> carries values to or from a worker while it runs; see std.Channel.
  • std::cpuCount() returns the number of processors that are online, at least 1, for sizing a pool of workers.

Parallel sums and the spawn-time snapshot

use io::console;
use std;
use std::Worker;

int sumRange(int from, int to) {
    int total = 0;
    for (int i in from..to) { total += i; }
    return total;
}

Worker<int> low = std::spawn(() => sumRange(1, 500));
Worker<int> high = std::spawn(() => sumRange(501, 1000));
int a = await low;
int b = await high;
console.writeln("low=${a} high=${b} total=${a + b}");
console.writeln("cpuCount is at least 1: ${std::cpuCount() >= 1}");
low=125250 high=375250 total=500500
cpuCount is at least 1: true

Rules

  • A collection verb inside a worker changes the worker's own copy of the collection, in every build, --lib included.
  • Copy always. What crosses a thread boundary is copied by flattening and rebuilding. The values that can cross are: numbers, char, bool, None, strings, ranges, struct values, Array and Map of such values, and classes whose shape is known statically (with shared parts and cycles preserved).
  • Some things cannot cross. A nested closure (only the spawn body itself may be a closure), an object tied to a descriptor or to the event loop (TcpStream, TcpListener, Timer, Process, and a disposable InStream such as a signal::on subscription), a Block, and a Worker or Promise handle are all rejected with a catchable error that names the type. Each worker opens its own sockets and timers. To talk to a worker, pass a Channel<T>, or await the Worker<T> that spawn returned.
  • Guard the spawn call. A body that is not a closure throws a catchable RuntimeException at the spawn call, and no worker starts. A try that wraps only the await does not catch it.
  • Failures arrive at the join. If the body throws, the worker rejects, and await rethrows the body's exception object (its class is preserved; an exception that cannot cross the thread boundary — one holding a closure, say — arrives as a RuntimeException naming why). A promise the body rejected and never awaited counts as a failure of the worker too: when the body finishes, the oldest such rejection becomes the worker's exception. A body that waits forever fails with the drained-loop RuntimeException, and the join sees that failure — the worker's wait is always judged before the spawner's own.
  • A worker's timers are its own. On a thread the worker finishes only after the timers and watches its body registered have run. On an engine without threads the body is a task of the program's one loop, and such callbacks run as ordinary program callbacks after the join; their rejections are the program's, not the worker's. Keep a body's work inside the body.
  • Let the spawning thread print. The deterministic way to write worker programs is: workers compute and return or send; only the spawning thread prints, after the join. Printing from a worker body races with other output.
  • Top-level variables are snapshotted too. A worker runs on its own copy of the program's top-level variables and static fields, taken when spawn is called. It does not see a store the spawner makes after the spawn, and a store the worker makes, directly or through a top-level object, stays in its copy and ends with it: send results back with return or a Channel. The copies keep sharing within one snapshot (two variables naming one object name one copy), and a closure a variable holds is copied with its captures. A value with no copy (a Promise, a Block, a file or socket handle) stays shared while the object holding it is copied; spawn rejects a Promise the body names through a variable. The copy follows references to a depth of 2,000; past that, the rest of a long list stays shared. A library built with --lib follows the same rule. A worker an export spawns runs on a copy of the spawning thread's top-level variables, and each C thread that calls leviathan_init gets its own copy of them as the library's top-level code left them, so a top-level variable written on one host thread is not seen by another. A thread's leviathan_init after its leviathan_shutdown starts again from that copy.
  • Real parallelism needs the native backend. On the compiled backend a worker is a real operating-system thread with its own heap and event loop; the results are identical to the cooperative way the interpreters run workers one after another.

Examples

The snapshot is taken when spawn is called. Here the worker computes with 10 and a box whose value was 10, even though the originals change right after:

Captures are copied at spawn

use io::console;
use std;
use std::Worker;

class Box { int value = 10; }

void demo() {
    Box box = Box();
    int limit = 10;
    Worker<int> w = std::spawn(() => limit * box.value);
    limit = 99;
    box.value = 5;
    console.writeln("worker computed ${await w}");
    console.writeln("original box still changed: ${box.value}");
}
demo();
worker computed 100
original box still changed: 5

Notes

Immutable data could be shared between threads without copying, but sharing is not part of the model.

See also

  • Worker — The handle to a value that another worker is computing.
  • Channel — A queue that carries values from one worker to another.
  • Promise — A value that arrives later.
  • TaskGroup — A set of tasks that live and end together.