Taking Turns
● Advanced4 minBefore this: TasksSpec 9.7
Tasks take turns in an order the language defines, so a program with tasks prints the same thing on every run.
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
Step through it:
at 0 ms
mainruns
slownot started
fastnot started
printed
step 1 of 6
main runs. spawn starts a task and makes it ready; the task that spawned it keeps running.
spawnmakes the new task ready; the task that spawned it keeps running.- A task runs until it waits. Then the task that became ready first runs.
- When no task is ready, the program waits for the earliest of them.
Why it matters: a bug in a program with threads often shows up once in a hundred runs. With fixed turns, the same program does the same thing every time, so a bug that happens once happens every time, and can be found.
What Kavach does for you
Tasks take turns in a fixed order
The order in which tasks take turns is defined, so a concurrent program prints the same thing on every run, and a bug shows up every time.