Tasks and Concurrency
FScript supports concurrent thunk execution through the default Task module surface.
Task.spawn and Task.await are provided by the default runtime extern registry, so an embedding host may choose not to expose them.
Task type
Task values use the native postfix type form:
'a task
Examples:
int task
string list task
Tasks are opaque handles. You create them with Task.spawn and observe them with Task.await.
Spawning work
Task.spawn schedules a thunk for concurrent execution and returns immediately.
let work =
Task.spawn (fun () -> 21 * 2)
Signature:
Task.spawn : (unit -> 'a) -> 'a task
FScript writes unit -> 'a in the type, and fun () -> ... is the preferred way to express that thunk.
Awaiting results
Use Task.await to wait for completion and extract the result value.
let work = Task.spawn (fun () -> 21 * 2)
let answer = Task.await work
Console.writeLine $"{answer}"
Signature:
Task.await : 'a task -> 'a
Concurrency model
- Spawned thunks run concurrently on the host runtime thread pool.
- Side effects may interleave across tasks and with the main script.
Task.awaitis the explicit synchronization point for a task result.
Failure model
FScript errors are fatal. Tasks follow the same rule.
- If a spawned thunk fails, the task has failed.
Task.awaiton that task fails the script with the same fatal runtime error.- Finishing a program with unawaited tasks is also a runtime error.
There is no catch/recovery mechanism in FScript today.
Example
let a = Task.spawn (fun () -> 40 + 2)
let b = Task.spawn (fun () -> 10 * 3)
let result = (Task.await a, Task.await b)
Console.writeLine $"{result}"
For a larger example, see samples/parallel-quicksort.fss.