Concurrency patterns

Three shapes cover most concurrent programs. A pipeline sends each item through stages that run at the same time. A pool gives each item to one of several identical workers. A fan-out with a collector sends one job to many workers and gathers their partial results. In Erlang each shape is a set of processes and tagged messages, with no thread API to learn.

A pipeline

A stage is a process that receives an item, works on it, and sends the result on. The stages overlap: stage two handles its first item while stage one works on the second. This small pipeline has one stage that doubles a number:

pipeline.erl

-module(pipeline). -export([main/0]). stage(Parent) -> receive {item, N} -> Parent ! {done, N * 2} end. main() -> Parent = self(), Pid = spawn(fun() -> stage(Parent) end), Pid ! {item, 21}, receive {done, Value} -> io:format("~p~n", [Value]) end.

erlc pipeline.erl

erl -noshell -eval 'pipeline:main(), halt().'

42

A real pipeline loops over the input and ends with a sentinel, or closes a socket when the input ends. The pattern is the same as a shell pipeline, with a process in place of each program and a message in place of a line.

A pool of workers

A pool starts a fixed number of identical workers and hands each one item. The parent collects the answers, and because the workers finish in any order, the collector sorts the result before it prints. This pool of three workers multiplies its item by ten:

pool.erl

-module(pool). -export([main/0]). worker(Parent) -> receive {job, N} -> Parent ! {done, N * 10} end. main() -> Parent = self(), Workers = [spawn(fun() -> worker(Parent) end) || _ <- lists:seq(1, 3)], [Worker ! {job, N} || {Worker, N} <- lists:zip(Workers, [1, 2, 3])], Results = [receive {done, Value} -> Value end || _ <- Workers], io:format("~p~n", [lists:sort(Results)]).

erlc pool.erl

erl -noshell -eval 'pool:main(), halt().'

[10,20,30]

The collector is a list comprehension with a receive inside: one receive per worker, in any order, because each message matches the same pattern. The sort is not decoration; a transcript that printed the raw order would pass on one run and fail on another.

Fan-out and a collector

Fan-out sends one query to several workers and combines the partial answers. A search across shards, a page built from independent sections and a calculation split into ranges are the same shape. The collector knows how many answers to expect, because it started that many workers; a reference per job lets it match an answer to the worker.

When the workers are not identical, the collector tags the job with a key and stores the answers in a map. When one worker may never answer, the collector needs a timeout and a decision: return the partial result or fail the whole call. The message protocols lesson shows the timeout and the reference that make that decision safe.

The collector that waits forever

The pool above trusts that every worker answers. A worker that crashes before its reply leaves the collector in a receive that never matches, and the caller waits forever. In a small program the shell just sits there; in a service the request holds a connection until a client gives up.

Add a timeout to the collector and a monitor to each worker, and a dead worker becomes an answer. The OTP tool for the same job is pmap in lib/stdlib or a gen_server pool started by a supervisor; both are built from the primitives of this chapter, and neither leaves a caller without an answer.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What makes a pipeline a pipeline?

    Answer

    Each stage is a process and passes its result on

    The stages run at the same time and exchange items as messages.

  2. Why does the pool sort its results before printing them?

    Answer

    The workers finish in any order

    A process order is not fixed, so a page that printed the raw order would not replay.

  3. How many receives does the collector of the pool run?

    Answer

    One per worker

    The comprehension runs one receive per worker, and each takes one done message.

  4. What is the risk of a collector without a timeout?

    Answer

    It waits forever when a worker dies

    A worker that crashes before replying leaves the receive unmatched, and the caller blocks.

  5. What does this module print? -module(q1). -export([main/0]). stage(Parent) -> receive {item, N} -> Parent ! {done, N + 1} end. main() -> Parent = self(), Pid = spawn(fun() -> stage(Parent) end), Pid ! {item, 41}, receive {done, V} -> io:format("~p~n", [V]) end.

    Answer

    42

    The stage adds one and the parent prints the value from the done message.

  6. What does this module print? -module(q2). -export([main/0]). worker(Parent) -> receive {job, N} -> Parent ! {done, N * 2} end. main() -> Parent = self(), W1 = spawn(fun() -> worker(Parent) end), W2 = spawn(fun() -> worker(Parent) end), W1 ! {job, 3}, W2 ! {job, 4}, R = [receive {done, V} -> V end || _ <- [W1, W2]], io:format("~p~n", [lists:sort(R)]).

    Answer

    [6,8]

    The workers double their job, and the collector sorts the two answers.

  7. What does this module print? -module(q3). -export([main/0]). main() -> Parent = self(), Workers = [spawn(fun() -> receive {job, N} -> Parent ! {done, N} end end) || _ <- lists:seq(1, 3)], [W ! {job, I} || {W, I} <- lists:zip(Workers, [1, 2, 3])], R = [receive {done, V} -> V end || _ <- Workers], io:format("~p~n", [length(R)]).

    Answer

    3

    Three workers answer once each, so the collector holds three values.

  8. What does this module print? -module(q4). -export([main/0]). main() -> Parent = self(), spawn(fun() -> Parent ! {done, 1} end), receive {done, V} -> io:format("~p~n", [V]) end.

    Answer

    1

    The worker sends the value one and the parent prints it.

  9. Which primitive ties a reply to one job in a fan-out?

    Answer

    A reference from make_ref/0

    A unique reference identifies the job, so an answer can be matched even when workers differ.

  10. Why is a pool of processes cheaper than a thread pool in another runtime?

    Answer

    Erlang processes are lightweight and scheduled by the VM

    An Erlang process is small and the VM schedules many of them on its own schedulers.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev