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.bodyis a closure with no parameters, andspawnreturns aWorker<T>whereTis the closure's result type.- A
Worker<T>is aPromise<T>, soawait workeris 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
spawncall. 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; seestd.Channel.std::cpuCount()returns the number of processors that are online, at least1, 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,
--libincluded. - 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,structvalues,ArrayandMapof such values, and classes whose shape is known statically (with shared parts and cycles preserved). - Some things cannot cross. A nested closure (only the
spawnbody itself may be a closure), an object tied to a descriptor or to the event loop (TcpStream,TcpListener,Timer,Process, and a disposableInStreamsuch as asignal::onsubscription), aBlock, and aWorkerorPromisehandle 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 aChannel<T>, orawaittheWorker<T>thatspawnreturned. - Guard the
spawncall. Abodythat is not a closure throws a catchableRuntimeExceptionat thespawncall, and no worker starts. Atrythat wraps only theawaitdoes not catch it. - Failures arrive at the join. If the body throws, the worker rejects, and
awaitrethrows the body's exception object (its class is preserved; an exception that cannot cross the thread boundary — one holding a closure, say — arrives as aRuntimeExceptionnaming 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-loopRuntimeException, 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
spawnis 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 withreturnor aChannel. 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 (aPromise, aBlock, a file or socket handle) stays shared while the object holding it is copied;spawnrejects aPromisethe 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--libfollows 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 callsleviathan_initgets 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'sleviathan_initafter itsleviathan_shutdownstarts 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.