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 task = task.async(fn() { do_some_work() }) let value = do_some_other_work() value + task.await(task, 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
pub type AwaitError {
Timeout
Exit(reason: Dynamic)
}
Constructors
-
Timeout
-
Exit(reason: Dynamic)
Functions
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.
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.
pub fn await_forever(task: Task(a)) -> a
Wait endlessly for the value computed by a task.
Be Careful! Like try_await_forever
, this function does not return until there is a value to
receive.
If the task process crashes then this function crashes.
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.
pub fn try_await_forever(task: Task(a)) -> Result(a, AwaitError)
Wait endlessly for the value computed by a task.
Be Careful! This function does not return until there is a value to receive. If a value is not received then the process will be stuck waiting forever.