async
Spawn concurrent tasks, wait for them, run all in parallel, race to first result, sleep.
Load with: use async
What this module does
async is a thin, clean wrapper over the runtime's concurrency syscalls.
It gives you five operations: spawn a function as a concurrent task, wait for a task handle to complete,
run a list of functions all at once and wait for all of them, race a list of functions and take the first result,
and sleep for a number of milliseconds.
Both the individual function names (asyncsp, asyncwt, etc.) and the
async object aliases (async.spawn, async.wait, etc.) are available.
The async object is defined at module load time.
The underlying primitives are __sys_spawn, __sys_wait, and __sys_sleep_ms
- these are host runtime syscalls.
Quick example
use async
# Spawn a background task
h = async.spawn(\() fetch_data("https://api.example.com/a"))
# Do other work here...
# Wait for it to finish and get the result
result = async.wait(h)
# Run several tasks in parallel and wait for all
results = async.all([
\() fetch("https://api.example.com/a"),
\() fetch("https://api.example.com/b"),
\() fetch("https://api.example.com/c")
])
# Sleep for 500ms
async.sleep(500)
Functions
Task control
asyncsp(fn) / async.spawn(fn)
Spawns fn as a concurrent task using __sys_spawn. Returns a handle you can pass to asyncwt/async.wait.
asyncwt(handle) / async.wait(handle)
Blocks until the task associated with handle completes, then returns its result. Uses __sys_wait.
asyncall(fns) / async.all(fns)
Spawns all functions in the list concurrently, then waits for each one in order. Returns a list of results in the same order as the input functions.
asyncrace(fns) / async.race(fns)
Spawns all functions in the list concurrently, then waits for the first one (index 0) and returns its result. The other tasks continue running but their results are discarded. This is a first-element race, not a true any-completes race.
asyncslp(ms) / async.sleep(ms)
Suspends the current task for ms milliseconds using __sys_sleep_ms.
Notes
async.racewaits for the task at index 0 specifically - not whichever finishes first. It spawns all tasks, but only waits on the first handle.- All five functions are also accessible as properties of the
asyncobject:async.spawn,async.wait,async.all,async.race,async.sleep. - Requires the host runtime to provide
__sys_spawn,__sys_wait, and__sys_sleep_ms.