<!-- Concurrency without colours · Tin · https://tin.ad/docs/tour/concurrency/ · generated from the built page -->

[Tour](https://tin.ad/docs/tour/) · 6 of 8

# Concurrency without colours

There is no `async` keyword. Any function can suspend, and callers don’t have to know. `spawn` starts a task, `await` waits for it, and no task outlives its parent.

*examples/09-concurrency.tin · tin run examples/09-concurrency.tin*

```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
}
```

<!-- output -->
```text
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]
```

Durations are literals: `60ms`, `2s`. The runtime runs on the host's event
loop, so a sleeping task never blocks the others. Agents are built on the same machinery, which is
why the next chapters can run several of them at once with nothing new to learn.

Tasks are structured: a task can't outlive the task that spawned it, `t.stop()` cancels a
whole tree, and `within(task, 30ms)` waits a limited time and hands back an
`Option`.

*examples/25-tasks.tin · tin run examples/25-tasks.tin*

```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()}")
}
```

<!-- output -->
```text
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
```

Time is a unit, and so is rate. `135Hz` is a `Frequency`, `1 / 135Hz` is
a `Duration`, and mixing them up (`135Hz + 7ms`, `sleep(135Hz)`) doesn't
compile. That's the kind of bug a robot's control loop can't afford.

*examples/18-rates.tin · tin run examples/18-rates.tin*

```tin
// Frequency is a unit, like Duration.
//
// `135Hz` is a Frequency and `7ms` a Duration. They turn into each other with
// `1 / x`, and a Duration times a Frequency is a plain number of cycles.
// Mixing them up is a compile error: `135Hz + 7ms`, `sleep(135Hz)`, `135Hz + 3`.

/// How a robot's control loop is scheduled.
type Loop = { name: string, rate: Frequency }

fn period(l: Loop): Duration => 1 / l.rate

fn ticksIn(l: Loop, window: Duration): int => int(floor(window * l.rate))

fn main() {
  let loops = [
    Loop { name: "balance", rate: 135Hz },
    Loop { name: "vision", rate: 30Hz },
    Loop { name: "planner", rate: 1 / 500ms },
  ]
  for l in loops {
    print("{l.name}: {l.rate}, every {period(l)}, {ticksIn(l, 2s)} ticks in 2s")
  }
  let fastest = loops.map(l => l.rate / 1Hz).reduce(0.0, (a, b) => max(a, b))
  print("fastest: {fastest * 1Hz}")
}
```

<!-- output -->
```text
balance: 135Hz, every 7.407ms, 270 ticks in 2s
vision: 30Hz, every 33.333ms, 60 ticks in 2s
planner: 2Hz, every 500ms, 4 ticks in 2s
fastest: 135Hz
```
