task - operations on spawned computations
Enable with use task;. Builtins for observing, joining, cancelling and bounding task of T values produced by spawn { ... } blocks, and for bounding what a task allocates.
For when to use spawn, value-semantics capture, and the exit-time loud-fail contract, see ../user-guide/concurrency.md.
use io;
use task;
def t as task of int init spawn { return 1 + 1; };
def n as int init task.wait($t);
io.printf("%d\n", $n); # 2Surface
| Call | Returns | Notes |
|---|---|---|
task.wait($t) | T | Block until $t finishes; return its value, or re-raise its error. |
task.poll($t) | bool | Non-blocking: true once $t has completed (value or error available). |
task.discard($t) | null | Mark $t fire-and-forget so the exit-time loud-fail skips it. Does not block. |
task.waitAll($ts) | list of T | Wait for every task in $ts; results in list order; re-raises the first error if any. |
task.waitAny($ts) | int | Block until any task in $ts is done; return its index. Caller follows up with task.wait. |
task.cancel($t) | null | Request cooperative cancellation of $t (see "Cancellation"). Does not block. |
task.cancelled() | bool | Non-raising poll: true if the current spawn body has been cancelled (always false on main). |
task.waitTimeout($t, ms) | T | Like task.wait, but throws a catchable Error{kind: "timeout"} if $t doesn't finish in ms (ms up to ~9.2e12; a larger value is a catchable error, not a silent instant timeout). |
task.waitAnyTimeout($ts, ms) | int | Like task.waitAny, but throws a catchable Error{kind: "timeout"} if none finishes in ms. |
task.waitAllTimeout($ts, ms) | list of T | Like task.waitAll, but throws a catchable Error{kind: "timeout"} if not all finish in ms; the tasks keep running. |
task.setAllocBudget(bytes) | null | Give the calling task an allocation budget (see "Allocation budget"); math.MAX_INT lifts the limit. |
task.allocatedBytes() | int | Bytes counted so far by the calling task's budget; 0 without one. |
task.wait is the core call; the rest are conveniences or non-blocking variants. More complex patterns compose from these.
Error propagation
A task of T carries either a value or an error after its body finishes. task.wait returns the value or re-raises the error at the wait call, where an enclosing try/catch catches it like any runtime error. The error keeps the position where it happened in the spawn body:
use task;
def t as task of int init spawn {
def xs as list of int init [];
return $xs[5]; # out-of-bounds inside the spawn
};
try {
def n as int init task.wait($t); # rethrown here
} catch (e) {
io.printf("caught: %s\n", $e.message); # "list index 5 out of bounds (len 0)"
}A task.wait marks the task observed whether it returns or re-raises. task.discard($t) also marks a task observed; use it for fire-and-forget.
Exit-time loud-fail
A task that ends in an error and is never observed (never task.wait'd, never task.discard'd) has its error printed to stderr at program exit, and the process exits non-zero, so no spawn error disappears silently.
Use task.wait when the result is needed and task.discard($t); when it is not; both make the intent visible at the call site.
use task;
def alive as task of null init spawn {
# ... long-running background work ...
return null;
};
task.discard($alive); # explicit fire-and-forgetWhen the program runs to its end, the loud-fail scan waits for every unobserved task to complete. A spawn { while (true) { ... } } without task.discard therefore hangs the program at exit; pair a body that may not terminate with an explicit task.discard.
Working with collections of tasks
task.waitAll($ts)
Spawn N units of work, wait for all results in order.
use task;
func worker(n as int) {
return $n * $n;
}
def tasks as list of task of int init [];
def i as int init 1;
while ($i <= 4) {
$tasks[] = spawn { return worker($i); };
$i = $i + 1;
}
def squares as list of int init task.waitAll($tasks);
# $squares is [1, 4, 9, 16]If any task in the list ended in an error, waitAll drains every other task (so the loud-fail stays quiet) and then re-raises the first error in list order. The other errors are observed but not surfaced; to get them, wait on each task individually inside a try / catch.
task.waitAny($ts)
First to finish wins. Returns the index of the first completed task (the lowest index when several are already done); follow up with task.wait($ts[$idx]) to read the result and mark it observed. The losing tasks keep running; observe or task.discard them so the loud-fail doesn't report them.
use task;
def fast as task of int init spawn { return 1; };
def slow as task of int init spawn {
# imagine more work here
return 2;
};
def candidates as list of task of int init [$fast, $slow];
def winner as int init task.waitAny($candidates);
def value as int init task.wait($candidates[$winner]);
task.discard($candidates[1 - $winner]); # release the losertask.waitAny([]) is a positioned runtime error.
Cancellation
task.cancel($t) requests cooperative cancellation: it sets a flag the spawned body observes at its next loop checkpoint (the start of any while / for / for-each / repeat iteration), where the runtime raises a catchable "task cancelled" error (kind "cancelled"), stopping the loop and the spawn at a safe point. The tree-walker cannot preempt a goroutine; a non-loop computation is instead bounded by the call-depth guard.
A non-terminating spawn can thus be cancelled. A body blocked in time.sleep, channel.send / recv / select (and their timeout forms), a task wait (wait, waitAll, waitAny and their timeout forms), os.waitTimeout / waitBytesTimeout or a socket read (net.readBytes, readN, readAll, UDP recvFrom, and so the http module's requests) wakes at once and the call raises the same "task cancelled"; a cancelled request's deferred net.close then frees its socket. This holds in an imported module's functions too, not only in the spawn body's own code. A task blocked in another system call - net.accept, term.readByte - does not see the flag until that call returns. Unblock it by closing its socket from another task (the blocked call raises a catchable Error{kind: "closed"}), or task.discard it. A program that ends by exit or an uncaught error does not wait for still-running tasks at all; one that runs to its end waits for every task nobody discarded.
A task.wait on a task that can never finish (a wait cycle, a body blocked on an unfed channel) hangs the program; Go's deadlock abort does not fire.
def t as task of int init spawn {
def n as int init 0;
while (true) { $n = $n + 1; }
return $n;
};
task.cancel($t);
task.discard($t); # cancel + discard: stop and forgetClean partial results use try / catch: catch the raised "task cancelled" inside the body and return the partial value.
def t as task of int init spawn {
def n as int init 0;
try {
while (true) { $n = $n + 1; }
} catch (e) {
# cancelled - fall through with the partial count
}
return $n;
};
task.cancel($t);
def partial as int init task.wait($t); # a clean value, not an errortask.cancelled() is a non-raising poll of the current body's cancel flag, for use at an arbitrary point (e.g. before an expensive step). It does not suppress the loop-checkpoint raise; use the try / catch idiom above to exit a loop cleanly.
task.cancel does not wait and does not mark the task observed. The idiom to stop-and-forget is task.cancel($t); task.discard($t);. A task.wait on a cancelled task whose body did not catch the error re-raises the "task cancelled" error (catchable). Cancelling an already-finished task is a no-op.
Timeouts
task.waitTimeout($t, ms) is task.wait bounded by a millisecond deadline: it returns the result (re-raising a body error, exactly like wait) if $t completes within ms, and otherwise throws a catchable Error{kind: "timeout"} (message task.waitTimeout: timed out after N ms), the same kind net uses for its deadlines. task.waitAnyTimeout($ts, ms) is the multi-task form, returning the first finisher's index or throwing on timeout. task.waitAllTimeout($ts, ms) bounds waitAll by one deadline for the whole list. On a timeout the task(s) stay live and unobserved, so follow up with a retry, or task.cancel + task.discard. ms 0 polls: the result when the task (for waitAllTimeout: every task) has already finished, else the timeout at once. A body error re-raised by waitTimeout keeps its own kind, so check kind to tell the two apart:
try {
def v as int init task.waitTimeout($t, 500); # up to 500 ms
} catch (e) {
if ($e.kind != "timeout") { throw $e; } # the body failed
task.cancel($t);
task.discard($t);
}Allocation budget
task.setAllocBudget(bytes) makes the calling task count the bytes it allocates; once the count passes bytes, the task's next counted operation throws a catchable Error{kind: "limit"} naming the budget and the count. Only that task is stopped: other tasks, and the process, go on. The guard is for work that may build a huge value (a request handler, a decoder fed by a client), which would otherwise run the whole process out of memory.
use task;
def t as task of int init spawn {
task.setAllocBudget(64 * 1024 * 1024);
try {
return buildReport();
} catch (e) {
if ($e.kind != "limit") { throw $e; }
return -1; # over budget: give up on this one
}
};| Counted | An eager copy (def, assignment, a parameter), an append, an index write (and the cells a new key adds), a field write, string + and interpolation, a list / map / struct / enum literal, a materialised range or slice, and every builtin's result |
| Size | One Value cell (48 bytes) per list element and struct field, two per map entry, the bytes of a bytes, the bytes of a new string. An eager copy, a copied literal element and a slice count every level of the copied value; a builtin's result counts its own level plus the level below, extrapolated from the first 8 elements |
| Cumulative | Bytes allocated, not live: a value that is dropped stays counted, and $s = $s + $x in a loop counts every intermediate string |
| A second call | Changes the limit and keeps the count; math.MAX_INT lifts the limit, the count goes on |
0 or negative | Throws (kind "runtime") |
| Spawned tasks | A task spawned by a task with a budget shares it (count and limit); a task without one spawns tasks without one |
| Nested | A task that sets a budget while running under one it inherited gets its own, nested: its bytes count toward both, either limit throws, and task.allocatedBytes() reads its own |
| After a throw | The task gets 1 MiB of room to handle the error (log, answer); one that keeps allocating throws again |
| Without a budget | Nothing is counted; the cost is one pointer check per counted operation |
The count is an estimate taken where the interpreter can see the value, not a measurement of the Go heap: a builtin that allocates a large buffer and returns a small value is counted by its result, and one huge allocation is counted after it is made (the library caps, kind "limit" as well, bound those). Size a budget from task.allocatedBytes() logged by a representative run, with headroom. The web module sets one per request with web.allocBudget.
Errors
The boundary checks are uniform across the library:
| Case | Message |
|---|---|
| Wrong argument count | task.wait expects 1 argument (task), got 2 |
| Wrong type | task.wait: argument must be a task, got int, task.waitAll: argument must be a list of task, got string, task.waitAll: element 2: argument must be a task, got int |
Empty list to waitAny | task.waitAny: list is empty (no tasks to wait on) |
ms negative | task.waitTimeout: timeout (ms) must be >= 0, got -1 |
ms too large | task.waitTimeout: timeout (ms) 99999999999999999 is too large (max 9223372036854) |
Budget 0 or negative | task.setAllocBudget: bytes must be > 0 (math.MAX_INT for no limit), got 0 |
These are kind "runtime"; a timeout is "timeout", a cancelled wait "cancelled", a passed allocation budget "limit". All errors are positioned at the call site. Errors re-raised by task.wait carry the position from the spawn body, so the report shows the actual fault location.
See also
- ../user-guide/concurrency.md - worked examples: when to spawn, value-semantics capture, the loud-fail contract, what Jennifer leaves out.
- ../technical/interpreter.md > Concurrency - internals: goroutine mapping, frame snapshot, error routing, registry, exit-time scan.
Academy talks
| Talk | What it shows |
|---|---|
| Advanced programming with Jennifer | waiting, cancelling and deadlines for spawned tasks |
| Jennifer facing hostile input | deadlines and cancellation for work on hostile input |
| Queues and messaging: Resque, AMQP, MQTT and ZeroMQ | consumers and a worker pool in spawned tasks |