Tasks
Also known as: thread async await spawn join future promise goroutine background parallel
● Advanced5 minBefore this: Functions, ErrorsSpec 9.1
spawn starts a task that runs alongside the rest of the program; .wait() gets its result. There is no async and no await.
const task = spawn work(…)
// … other work meanwhile …
const result = try task.wait()fn slow_double(n: Int) -> Int {
n * 2
}
fn main() ! Error {
const t = spawn slow_double(21)
print("working meanwhile")
print(try t.wait())
}The program ran and printed:
kavach run spawn.kav
working meanwhile42
- Any function can be spawned, and any function can wait: no function is marked
async, so there are no two kinds of functions to keep apart. - While a task waits, for the network, time or another task, the others run.
- Tasks are light: a server can run one per connection, many at once.
Two things at once
use std.time
fn report(name: String, ms: Int) -> String {
time.sleep_ms(ms)
print("{name} done")
name
}
fn main() ! Error {
const slow = spawn report("slow", 200)
const fast = spawn report("fast", 100)
print("both started")
print("{try slow.wait()} and {try fast.wait()} are back")
}The program ran and printed:
kavach run turns.kav
both startedfast doneslow doneslow and fast are back
The two sleeps overlap, so the program takes about 200 ms, not 300. Why it prints in exactly this order is on Taking Turns.
One page for each form
Try it yourself
Spawn three tasks that sleep 300, 100 and 200 ms and print their names. In what order do they print?
Show the answer
By how long each sleeps: the 100 ms one, then 200, then 300. A task whose wait ends first becomes ready first.
Check yourself
QUIZ 1 / 1pick one
A function calls
time.sleep_ms(100) inside a task. What do the program's other tasks do meanwhile?