gleam/otp/task
A task is a kind of process that performs a single task and then shuts down. Commonly tasks are used to convert sequential code into concurrent code by performing computation in another process.
let t = task.async(fn() { do_some_work() })
res = do_some_other_work()
res + task.await(t, 100)
Tasks spawned with async can be awaited on by their caller process (and only their caller) as shown in the example above. They are implemented by spawning a process that sends a message to the caller once the given computation is performed.
There are two important things to consider when using async
:
-
If you are using async tasks, you must await a reply as they are always sent.
-
async tasks link the caller and the spawned process. This means that, if the caller crashes, the task will crash too and vice-versa. This is on purpose: if the process meant to receive the result no longer exists, there is no purpose in completing the computation.
This module is inspired by Elixir's Task module.
Types
AwaitError
pub type AwaitError { Timeout Exit(reason: Dynamic) }
Constructors
-
Timeout
-
Exit(reason: Dynamic)
Task
pub opaque type Task(value)
Functions
async
pub fn async(work: fn() -> a) -> Task(a)
Spawn a task process that calls a given function in order to perform some
work. The result of this function is send back to the parent and can be
received using the await
function.
See the top level module documentation for more information on async/await.
await
pub fn await(task: Task(a), timeout: Int) -> a
Wait for the value computed by a task.
If the a value is not received before the timeout has elapsed or if the task process crashes then this function crashes.
try_await
pub fn try_await( task: Task(a), timeout: Int, ) -> Result(a, AwaitError)
Wait for the value computed by a task.
If the a value is not received before the timeout has elapsed or if the task process crashes then an error is returned.