Tasks and Agents
A Task in Elixir is a process started for one computation whose answer the caller needs. The pair Task.async/1 and Task.await/1 starts the work, lets the caller do something else, and then collects the result. An Agent is the other small tool of the same family: a process that holds one value, with a function to read it and a function to change it. Both are built on the raw processes of the processes lesson.
Task.async and await
Task.async/1 starts the function in a new process and answers a task struct at once. Task.await/1 waits for that task and returns its value, so the work overlaps with the lines between the two calls:
task.exs
task = Task.async(fn -> Enum.sum(1..100) end) IO.puts("working") IO.inspect(Task.await(task))
elixir task.exs
working
5050
The default timeout of Task.await/1 is five seconds; the second argument changes it. A task is linked to the process that started it, so a crash inside the task ends the caller as well, which is the reason a task normally runs code the caller already trusts.
Several tasks at once
A list of tasks is collected with one call. Task.await_many/1 waits for all of them and returns the values in the order the tasks were given, not in the order they finish:
many.exs
tasks = [ Task.async(fn -> Enum.sum(1..10) end), Task.async(fn -> Enum.sum(1..5) end) ] IO.inspect(Task.await_many(tasks))
elixir many.exs
[55, 15]
The order of the answers follows the order of the list, whatever order the processes finish in, which makes the result easy to destructure. The next lesson, tasks in parallel, applies the same idea to a stream of work and limits how many tasks run at once.
A supervisor for tasks
A task started with Task.async/1 is linked to the caller, which is convenient until a failed task takes the caller down. Task.Supervisor starts tasks under a supervisor instead, and async_nolink/2 leaves the caller free to decide what a failure means:
supervised.exs
{:ok, supervisor} = Task.Supervisor.start_link() task = Task.Supervisor.async_nolink(supervisor, fn -> 6 * 7 end) IO.inspect(Task.await(task)) IO.inspect(Task.Supervisor.children(supervisor))
elixir supervised.exs
42
[]
The second line is empty because the task has finished, and a finished task is no longer a child. A failed no-link task answers {:exit, reason} to Task.yield/2 or Task.await/1 instead of raising in the caller, which is the shape a program uses when one failed job should not stop the rest.
An Agent is state in a process
An Agent wraps a value in a process. The function given to start_link/1 produces the initial value, and the caller reads or changes it through functions, never directly. Every change runs inside the agent, so two callers cannot interleave and lose an update:
agent.exs
{:ok, agent} = Agent.start_link(fn -> 0 end) Agent.update(agent, &(&1 + 2)) Agent.update(agent, &(&1 * 10)) IO.inspect(Agent.get(agent, & &1)) IO.inspect(Agent.get_and_update(agent, fn n -> {n, n + 1} end)) IO.inspect(Agent.get(agent, & &1))
elixir agent.exs
20
20
21
Agent.get/2 runs a function on the state and returns its result, so a caller reads only the part it needs. Agent.get_and_update/2 answers {value_to_return, new_state} in one step, which is how a counter hands out the old number and stores the new one without a window in between.
The mistake: update answers ok
Agent.update/2 answers :ok, not the new value. A reader who uses it as if it returned the state sees the atom and concludes that the update failed:
update.exs
{:ok, agent} = Agent.start_link(fn -> 1 end) IO.inspect(Agent.update(agent, &(&1 + 1))) IO.inspect(Agent.get(agent, & &1))
elixir update.exs
:ok
2
The update did happen; the second line shows the value. Read it back with Agent.get/2, or call Agent.get_and_update/2 when the call needs the value in the same step. The same split exists in the next chapter, where a GenServer returns {:reply, answer, state} from a call and only :noreply from a cast.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Task.async/1answer?Answer
A task struct, before the function has finished
async starts the work and returns at once; await collects the value later.
-
In what order does
Task.await_many/1return the results?Answer
The order of the task list
The results follow the task list, not the finish order.
-
What is the difference between
Task.async/1andTask.Supervisor.async_nolink/2?Answer
async links the task to the caller; async_nolink does not
async links the task to its caller, so a crash propagates; async_nolink leaves the caller alive.
-
What does
Agent.update/2return?Answer
:ok
update answers :ok; read the state with get/2 or use get_and_update/2.
-
What does this program print?
task = Task.async(fn -> 2 * 21 end) IO.inspect(Task.await(task))Answer
42
await waits for the task and returns the value of the function.
-
What does this program print?
tasks = [ Task.async(fn -> 1 + 1 end), Task.async(fn -> 2 + 2 end) ] IO.inspect(Task.await_many(tasks))Answer
[2, 4]
await_many keeps the order of the list, so the first result comes from the first task.
-
What does this program print?
{:ok, agent} = Agent.start_link(fn -> 5 end) Agent.update(agent, fn n -> n * 2 end) IO.inspect(Agent.get(agent, fn n -> n end))Answer
10
update changes the state to 10, and get returns it.
-
What does this program print?
{:ok, agent} = Agent.start_link(fn -> 5 end) IO.inspect(Agent.get_and_update(agent, fn n -> {n, n + 1} end)) IO.inspect(Agent.get(agent, fn n -> n end))Answer
5 then 6
get_and_update returns the old value and stores the new one, which the next get reads.
-
A task started with
Task.async/1raises. What happens to the caller by default?Answer
The caller ends as well, because the task is linked
async links the task to the caller, so the failure propagates unless a no-link task is used.
-
Which tool fits a program that needs one value shared by several callers, with no custom messages?
Answer
An Agent
An Agent is the smallest tool that holds one value behind a process; a Task is for one computation.
Автор статьи: Arthur Isaev