Threads and servicesSlide 45 of 86
45awaitThreads and services

Concurrency: await

Grammar: await-all
await[call,call,]
await-all = "await" "[" call { "," call } [ "," ] "]" ;As the compiler reads it; §2.6 of the specification is out of date here.

await [f(a), g(b)] starts every call in the list on a thread of its own and waits for all of them, as one barrier. It is the only form of await:

  • Every entry has to be a call; a value already in hand has nothing to wait for.
  • The calls answer with one type, and the barrier resolves to a vector of them as long as the list, so its elements are indexed without a guard. For calls that answer with different types, name each one with x := async f() instead.
  • Over calls that answer with nothing there is nothing to resolve to, so it is a statement: run all of these, then carry on.
  • An await of one call is allowed; await [] is a compile error.

Each call's arguments are copied before its thread starts, as with async, and a call cannot be cancelled once it has started.

Many at once, as a value
proc slow(label: Str, ms: Int): Str {
	hive.task.sleep(ms)
	return label
}

proc main(): void {
	both := await [slow("a", 40), slow("b", 40)]   // one barrier, a Str[2]
	echo both
	echo both[1]                                    // a static length: no guard
}
Many at once, as a statement
proc note(text: Str): void {
	hive.task.sleep(20)
	echo text
}

proc main(): void {
	// Nothing to resolve to, so it is a statement: a batch of side effects
	// finished before the next line, each on its own thread.
	await [note("first"), note("second")]
	echo "both notes are in"
}