Examples · 9 of 339
09-concurrency
The event loop, without coloured functions.
tin run examples/09-concurrency.tin// The event loop, without coloured functions.
//
// There is no `async` keyword. Any function can suspend — `sleep` below does —
// and callers do not have to know. `spawn` starts a task; `await` waits for it.
fn brew(drink: string, wait: Duration): string {
print(" start {drink}")
sleep(wait)
print(" done {drink}")
"a cup of {drink}"
}
fn main() {
print("one after another:")
let t0 = now()
brew("tea", 60ms)
brew("coffee", 90ms)
let sequential = now() - t0
print("at the same time:")
let t1 = now()
let tea = spawn brew("tea", 60ms)
let coffee = spawn brew("coffee", 90ms)
let cups = [await tea, await coffee]
let concurrent = now() - t1
print(cups)
print(if concurrent < sequential { "spawning was faster" } else { "spawning was not faster?!" })
// fan out, then gather
let jobs = range(1, 6).map(n => spawn square(n))
var results: int[] = []
for job in jobs { results.push(await job) }
print(results)
}
fn square(n: int): int {
sleep(10ms * (6 - n))
n * n
} one after another:
start tea
done tea
start coffee
done coffee
at the same time:
start tea
start coffee
done tea
done coffee
["a cup of tea", "a cup of coffee"]
spawning was faster
[1, 4, 9, 16, 25]