Coroutines and workers
Do a calculation on another thread
The starting VM can wait for a result from the worker.
use task
func calculate(value):
return value + 2
print(task.wait(task.spawn(calculate, 5)))
7
The worker runs calculate() in its own VM and returns a copy of the result.
Coroutines
Use a coroutine to pause a computation and resume it on the same VM.
Workers and channels
Workers run in separate VMs on native threads. Use channels to communicate by sending copied messages.
Timers and background I/O
Use the 'task' module to schedule work, wait for a timer, or submit file operations.
Cancellation
Cancellation behavior depends on the kind of task. Cancelling a suspended coroutine runs its suspended 'finally' blocks.
A coroutine runs cooperatively in its caller's VM. Create it with create(coroutine, function, ...arguments). Each task.resume runs to the next yield or the final return and returns that value. A bare yield passes null. A nested Atom function can yield, subject to native call and module initialization boundaries. An unhandled error makes the coroutine failed. Resume only ready or suspended coroutines. Cancellation unwinds suspended finally blocks, skips catches and skips normal statements after the suspension. A running coroutine cannot be cancelled through its own handle.
A worker runs on a native thread in an isolated VM. Mutable arguments, transferable captures and results cross as copies, with cycles and aliases preserved within each copied graph. Built-in modules can be resolved in the worker when configured. Native functions, live FFI resources, files, sockets and other VM-owned handles cannot be transferred. A channel is a shared FIFO queue with copied message values. A worker may open its own permitted resources. File/network permissions and limits are inherited. Process control and FFI are restricted to the original VM. Cancel requests cooperative interruption. The VM cancels and joins outstanding workers on teardown.
task.wait waits for workers and timer/I/O tasks. Its optional timeout uses seconds. Timeout can be handled while leaving the task available for a later wait. task.after creates a timer that returns null. task.read and task.write perform file work in background VMs. task.parallel and task.group collect results in input order. For a bounded producer and consumer, close the channel to signal end of input, and drain queued messages before treating it as finished. See the task API and worker example.