Threads and servicesSlide 46 of 86
46withThreads and services

Concurrency: with timeout

Grammar: with-expr
postfix-exprwithtimeoutadd-exprcompiler
with-expr = postfix-expr [ "with" ( "timeout" add-expr | "compiler" ) ] ;

A wait can be bounded where it is written: f(x) with timeout 500, or await […] with timeout 500, in milliseconds. The wait then answers with a Result<T, hive.task.TimeoutError> instead of the value, so running out of time is a value to handle rather than a crash. A TimeoutError carries waited, the milliseconds asked for, and a message.

  • It abandons the waiting, not the work: a thread cannot be stopped from outside, so the call runs to its end, side effects included, and only its answer is dropped.
  • On an await, it is one deadline for the whole barrier, which fails as a whole.
  • A call that answers with nothing cannot be bounded, since the Result would have no value to carry. Nor can an async binding: its wait happens wherever its name is read.
  • A request to a service already answers with a Result, so there the deadline becomes that Result's own error, SyslinkError.Timeout, as the next slide shows.
proc slow(label: Str, ms: Int): Str {
	hive.task.sleep(ms)
	echo "{label} finished anyway"
	return label
}

proc main(): void {
	if slow("c", 100) with timeout 20 is Result.Error(err) {
		echo "gave up after {err.waited}ms"
	}
	hive.task.sleep(150)      // long enough to see the work finish regardless

	both := await [slow("a", 10), slow("b", 10)] with timeout 500
	if both is Result.Ok(labels) {
		echo labels
	}
}