Tour · 17 of 18
Concurrency
The program on the right runs two tasks together, races them, and times out a slow one.
#join!
let (a, b) = join!(first(), second())join! starts independent tasks and returns their values in order. Its
arguments have no !. first() describes work that has not started, and
join! starts it. first!() would run at once and pass a string instead.
#race!
println("race: ${race!(first(), second())}")race! returns the first value to complete and cancels the others. It
takes calls without ! too.
#Timeouts
apply!(timeout(1ms)):
let result: Result[string, TimedOut] = .Ok(too_slow!())
resulttimeout(1ms) limits how long the apply! block may wait. If time runs
out, the block gives .Err with a TimedOut. The limit is a Duration, so a
bare 1 is an error.
Run it. It prints join: first, second and race: first. too_slow!
sleeps 20 ms against a 1 ms limit, so the last line is timed out after 1ms.
Try it: change let (a, b) = join!(first(), second()) to let (a, b) = join!(first!(), second()) and press Run.
Run: Ctrl+Enter · Pages: Alt+← Alt+→