Examples · 25 of 339
25-tasks
Structured concurrency: tasks have owners, and waiting has limits.
tin run examples/25-tasks.tin// Structured concurrency: tasks have owners, and waiting has limits.
//
// - A task cannot outlive the task that spawned it. `await t` returns only
// when t and everything t started have finished.
// - `t.stop()` stops a task and everything beneath it.
// - `within` waits a limited time: Some(result), or the task is stopped
// and the answer is None.
fn download(name: string, time: Duration): string {
sleep(time)
print(" got {name}")
name
}
/// Starts two downloads and returns straight away. Its caller still sees it
/// as unfinished until both are done.
fn mirror(site: string): string {
spawn download("{site}/index", 150ms) // far apart, so the order holds on a busy machine
spawn download("{site}/logo", 20ms)
"{site} queued"
}
fn main() {
print("ownership:")
let job = spawn mirror("tin.dev")
print(await job) // printed after both downloads
print("a time limit:")
print(spawn download("small file", 10ms) |> within(1s))
print(spawn download("huge file", 1h) |> within(30ms))
print("stopping a tree:")
let big = spawn mirror("slow.example")
big.stop() // stops mirror and both of its downloads
sleep(50ms)
print("stopped: {big.stopped()}")
} ownership:
got tin.dev/logo
got tin.dev/index
tin.dev queued
a time limit:
got small file
Some("small file")
None
stopping a tree:
stopped: true