Language reference · Section 12
Tasks and concurrencyStage 5
12.1 spawn
spawn runs a function call as a task, a lightweight thread of work.
The program keeps going without waiting for it.
plant job = spawn download("https://example.com/a.txt")
drop("downloading...")
plant text = job.wait() # wait for the result (or its error)spawn returns a Task[T], where T is the call's result type.
task.wait() returns the result, or throws the task's error.
12.2 No async/await
Calls that wait for the outside world (network, files, timers, ask)
pause only the task that made them; other tasks keep running. Code is
written the same way whether or not it runs in a task: there is no
async, no await, and no separate "async" version of any library.
12.3 Sharing between tasks
Tasks do not share variables. A task gets its own copy of the values it is
given, and tree objects cannot be passed to a task (a compile error) unless
the tree is marked shared, which allows only fields that are themselves
values and makes each method call atomic. Tasks communicate through
channels:
plant ch = Channel[int]()
spawn (() => {
for i in 0..3 { ch.send(i) }
ch.close()
})()
for n in ch { drop(n) } # 0 1 2So there are no data races by construction. All tasks run on one operating system thread in 1.0; using several cores is planned after 1.0.
12.4 Taking turns
A task runs until it waits: for a channel, another task, a timer, or
input and output. Then the next task in line runs. time.sleep(0) gives
the others a turn. Channel[T]() has no limit; Channel[T](capacity: n)
makes send wait while n values wait to be received. for x in ch
receives until the channel is closed and empty, and receive() gives
none then.
Waiting can't happen inside a callback the runtime is running (the
function given to map or filter, a to_str): that is an Error.
time.sleep inside one simply waits, holding up the other tasks.
The program ends when its own code ends, stopping the tasks still running.
A task's error is thrown by wait(); one that nothing waited for is
printed when the program ends, and the exit code is 1. When every task
waits and nothing can wake them, the program ends with a deadlock error.