Tasks in parallel
A task in Elixir is one process for one computation. When a program has a hundred independent jobs of the same shape, starting a hundred tasks by hand is the wrong level of detail: Task.async_stream/3 takes an enumerable, starts one task per element, and hands the results back as a stream. The concurrency limit, the order and the timeout are options of that one call.
async_stream
The first argument is the enumerable, the second the function each element goes through. The result is a stream, so nothing starts until the stream is enumerated, and each element arrives as an {:ok, value} tuple:
stream.exs
results = 1..5 |> Task.async_stream(fn n -> n * n end) |> Enum.to_list() IO.inspect(results)
elixir stream.exs
[ok: 1, ok: 4, ok: 9, ok: 16, ok: 25]
The :ok in front of every value is the shape of a task result: a task can also end with an exit, and the stream reports both kinds in the same list. A program that wants the values alone maps over the tuples, as the next section does.
Order and no order
By default the results keep the order of the input, even though the tasks finish in another order: ordered: false returns each result as soon as it is ready. A program that sorts the values afterwards gains the earlier answer without depending on the finish order:
unordered.exs
results = 1..5 |> Task.async_stream(fn n -> n * n end, ordered: false) |> Enum.map(fn {:ok, n} -> n end) |> Enum.sort() IO.inspect(results)
elixir unordered.exs
[1, 4, 9, 16, 25]
With ordered: false the list is a report of the work, not a sequence that matches the input positions, so a program that needs the position keeps the default. Sorting is the price of the unordered form, and for a hundred thousand jobs it is a small price next to the waiting time.
The concurrency limit
max_concurrency caps how many tasks run at once. The default is the number of schedulers, which is the right number for CPU work; a smaller number is the right choice when every job opens a connection or reads a file:
limit.exs
results = 1..4 |> Task.async_stream(fn n -> {n, n * 2} end, max_concurrency: 2) |> Enum.to_list() IO.inspect(results)
elixir limit.exs
[ok: {1, 2}, ok: {2, 4}, ok: {3, 6}, ok: {4, 8}]
The limit does not change the results, only how many run together. The stream keeps at most two tasks alive, and the next element waits in the enumerable until one finishes, so a list of ten thousand jobs does not start ten thousand processes.
A task that is too slow
Each task has a timeout, five seconds by default. A task that runs longer ends with an exit, and on_timeout: :kill_task turns that exit into a value of the stream instead of a crash of the caller:
slow.exs
results = 1..2 |> Task.async_stream( fn n -> Process.sleep(200) n end, timeout: 50, on_timeout: :kill_task ) |> Enum.to_list() IO.inspect(results)
elixir slow.exs
[exit: :timeout, exit: :timeout]
Both tasks slept past the limit and were killed. Without on_timeout: :kill_task the call raises an exit in the caller, which is the right choice when a slow task means the whole job failed. The option is per stream, so a batch of jobs with one slow member can report that member and finish the rest.
The mistake: summing ok tuples
The values of the stream are tuples, and a function that expects numbers fails on the first one. The message names the tuple it was given and the addition it was part of:
sum.exs
total = 1..5 |> Task.async_stream(&(&1 * 2)) |> Enum.sum() IO.inspect(total)
elixir sum.exs
** (ArithmeticError) bad argument in arithmetic expression: {:ok, 2} + 0
:erlang.+({:ok, 2}, 0)
(elixir 1.19.7) lib/enum.ex:4570: anonymous fn/2 in Enum.sum/1
(elixir 1.19.7) lib/task/supervised.ex:421: Task.Supervised.stream_deliver/7
(elixir 1.19.7) lib/enum.ex:4570: Enum.sum/1
sum.exs:4: (file)
The fix is the map that unwraps the tuple, with a clause for the failure when the stream can fail: Enum.map(results, fn {:ok, n} -> n end). The same shape appears in Task.await_many/1 only for failures, while async_stream wraps every result, the successful ones included.
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_stream/3do with an enumerable?Answer
It starts one task per element, up to the concurrency limit
The stream starts a task for each element as it is enumerated, with a cap on how many run together.
-
What is the default value of
max_concurrency?Answer
The number of schedulers
The default follows the machine, one task per scheduler.
-
What does
ordered: falsechange?Answer
The results arrive as they finish, not in input order
The unordered form returns each result when it is ready, so the order no longer matches the input.
-
What does
on_timeout: :kill_taskdo?Answer
It kills the slow task and puts an exit tuple in the stream
The option turns a timeout into a value of the stream instead of an exit in the caller.
-
What does this program print?
results = 1..3 |> Task.async_stream(fn n -> n * 2 end) |> Enum.to_list() IO.inspect(results)Answer
[ok: 2, ok: 4, ok: 6]
Every element of the stream is an ok tuple, the successful ones included.
-
What does this program print?
results = 1..3 |> Task.async_stream(fn n -> n * 2 end, ordered: false) |> Enum.map(fn {:ok, n} -> n end) |> Enum.sort() IO.inspect(results)Answer
[2, 4, 6]
The map unwraps the tuples and the sort makes the order deterministic.
-
What does this program print?
1..2 |> Task.async_stream(fn n -> n + 1 end, max_concurrency: 1) |> Enum.to_list() |> IO.inspect()Answer
[ok: 2, ok: 3]
The limit changes how many run together, not the results or their order.
-
What does this program print?
1..2 |> Task.async_stream( fn n -> Process.sleep(200) n end, timeout: 50, on_timeout: :kill_task ) |> Enum.to_list() |> IO.inspect()Answer
[exit: :timeout, exit: :timeout]
Both tasks exceed the timeout and each becomes an exit tuple in the stream.
-
What does this program print?
1..2 |> Task.async_stream(&(&1 * 2)) |> Enum.sum() |> IO.inspect()Answer
an ArithmeticError, because the elements are {:ok, n} tuples
The stream wraps every value in :ok, and addition cannot take a tuple.
-
Which form suits a program that needs the result for each input element in the same position?
Answer
The default ordered stream
The default keeps the input order, so the n-th result belongs to the n-th element.
Автор статьи: Arthur Isaev