LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

class Worker<T>

The handle to a value that another worker is computing.

since 0.1.0-alpha.1linux

bases
Promise<T>

Overview

A Worker<T> is a Promise<T>, so await worker is the join: it waits for the result, rethrows the exception the worker's body threw if there was one (its class is preserved), and gives the value. Create one with spawn. Everything that crosses between the program and a worker is copied: the worker works on a snapshot of what its body captured when spawn was called, and its result is copied back at the join, so the two sides never share mutable data. A Worker or Promise handle cannot itself be passed to another worker; use a Channel to exchange values.

On Linux a worker runs on its own operating-system thread. Print results from the code that awaits the worker, not from inside its body, so the output order does not depend on thread timing.

Description

std::spawn(body) starts body as a worker and returns a Worker<T>. Worker<T> extends Promise<T>, so everything you can do with a promise you can do with a worker: await it, isReady(), get() once ready. Joining a worker is an ordinary await.

Joining a worker, and its failure

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

Worker<int> bad = std::spawn(() => {
    throw RuntimeException("worker failed");
    return 1;
});
try {
    int v = await bad;
    console.writeln("never printed ${v}");
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
Worker<string> fine;
fine = std::spawn(() => "ok");
console.writeln(await fine);
console.writeln(fine.isReady());
caught: worker failed
ok
true

A worker is not a task of your program: it is a separate thread of execution, and it cannot be cancelled. Use a TaskGroup for cheap, cancellable work on the same thread.

Rules

  • Awaiting a worker whose body threw rethrows the body's exception object at the await (its class is preserved; an exception that cannot cross the thread boundary arrives as a RuntimeException naming why). Catch it there.
  • The worker's result is copied back to the spawning thread, so what you receive is your own copy.
  • A Worker handle cannot cross a thread boundary. A spawn body must not use another Worker or Promise, whether captured from a local or reached through a global, and sending one through a channel throws an error that says to pass a Channel instead. Join a worker from the thread that spawned it.
  • A worker cannot be cancelled, and a timeout does not stop it: awaitTimeout only stops waiting.
  • Do not print from a worker body; return the data and print after the join.

Examples

See lang.threads for parallel sums and the spawn-time snapshot, and std.Channel for streaming results out of a running worker.

Notes

On the compiled backend a worker is a real thread; the interpreters run workers cooperatively. The results are the same.

Examples

Computing on a worker and joining

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

int compute() {
    int base = 10;
    Worker<int> w = std::spawn(() => {
        int total = 0;
        for (int i in 1..4) total = total + i * base;
        return total;
    });
    base = 1000;
    return await w;
}
console.writeln(compute());
100

Constructors

new

new()

Create a worker handle that has no body of its own.

The handle is pending until it is resolved or rejected. Programs normally get workers from spawn.

Examples

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

Worker<string> w = Worker();
w.resolve("settled by hand");
console.writeln(await w);
Worker<int> bad = Worker();
bad.reject(RuntimeException("rejected by hand"));
console.writeln(bad.failed);
try {
    int r = await bad;
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
settled by hand
true
caught: rejected by hand

See also

  • spawn — Run a function as a worker and return a handle to its result.
  • 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.