Callable execution in a new context with a cancellation deadline.


runFor

(callable out duration -- output timedOut) Runs callable in a new context under a deadline and returns its output and whether the deadline requested cancellation.
  • callable and out are passed to spawn, whose rules for them apply. With () as out, runFor returns timedOut alone.
  • output is made by new from the result of get on the context of callable, so Text and Code are not supported output schemas here; return an owned String instead of Text.
  • duration is the Real64 number of seconds from the call of runFor until the deadline and must be positive. Checked violations report invalid duration; a known violation can fail compilation. Run-time assertions require DEBUG.
  • A timer context requests cancellation of the context of callable if that context is still unfinished when the timer runs, at the deadline or later; timedOut is TRUE if the timer made the request and FALSE otherwise.
  • After callable has started, the scheduler checks the deadline only while no context is running and, on Linux and macOS, none is ready; a context that yields stays ready.
  • The cancellation does not terminate callable, which can observe it with canceled?: runFor returns only after callable has returned, and output is its output also when timedOut is TRUE.
  • If the calling context is already canceled, spawn is not called: timedOut is FALSE, and output is made from out by new.
  • runFor waits with get, so canceling the calling context meanwhile also requests cancellation of the context of callable; timedOut still reports the timer's request alone.

Examples

Example: completion and timeout

The first callable returns before its deadline; the timer cancels the second, cutting its sleep short.

"String"      use
"control"     use
"sync/runFor" use
"sync/sync"   use

{} Int32 {} [
  fast: fastTimedOut: [42] Int32 1.0r64 runFor;;
  slow: slowTimedOut: [10.0r64 sleepFor canceled? ["canceled" toString] ["finished" toString] if] String 0.01r64 runFor;;
  ("fast=" fast " timedOut=" fastTimedOut LF) printList
  ("slow=" slow " timedOut=" slowTimedOut LF) printList
  0
] "main" exportFunction

Expected Output

fast=42 timedOut=FALSE
slow=canceled timedOut=TRUE

See also