Threads and servicesSlide 44 of 86
44asyncThreads and services

Concurrency: async

Grammar: async-stmt, var-decl
asynccall
async-stmt = "async" call ;
mutIDENT:=expressionIDENT:=asynccall
var-decl = [ "mut" ] IDENT ":=" expression | IDENT ":=" "async" call ;As the compiler reads it; §2.5 of the specification is out of date here.

Every call waits for its callee unless you say otherwise — there is no async func and no future type. The call site decides:

  • f(x) waits for it.
  • async f(x), as a statement, starts it on a thread of its own and carries on without it.
  • x := async f(x) starts it too, and waits only where x is first read; every later read is free. A binding nobody reads still runs.

Either way, the thread gets a copy of every argument, worked out on the caller's side before it starts — so async save(build()) runs build() first, and nothing the caller does afterwards changes what the thread was given.

Where async may go:

  • Only as a statement or as the value of a declaration, and the binding cannot be mut.
  • Only before a call to a callable of your own or of the library — not a builtin, a constructor or a partial application, which do no work worth a thread.
  • Not bound to a call that answers with nothing, since the name would have nothing to hold.

A panic on a thread started with a binding is raised where the binding is read; a panic on a thread nobody waits for stops the whole program. When main returns, the program ends and takes any thread still running with it — unless a window is open, in which case it waits for its windows. hive.task.sleep(ms) parks only the calling thread, and hive.task.sleepForever() parks it for good.

Starting work and waiting for it
proc slow(label: Str, ms: Int): Str {
	hive.task.sleep(ms)
	return label
}

proc main(): void {
	a := async slow("a", 30)      // starts now
	b := async slow("b", 30)      // starts now, alongside
	echo "{a} and {b}"             // waits for both, right here: about 30ms, not 60
}
Fire and forget
proc note(text: Str): void {
	hive.task.sleep(20)
	echo text
}

proc main(): void {
	async note("from another thread")
	echo "main carries on"
	hive.task.sleep(50)         // without this, main would return first
}                               // and take the other thread with it