Selective receive

A mailbox is a queue, and receive is not limited to its head. Each clause is a pattern, the runtime scans the queue for the first message that matches any of them, and the messages it skips stay in place. That is selective receive: the process takes the answer it needs and leaves the rest, and it is also the source of the one performance trap of the model.

A pattern picks the message

Two messages arrive in the order low, high, and the first receive asks for high. The runtime skips low, takes high, and leaves low for the next receive. The order of the clauses is also the order a message is tried against them:

priority.erl

-module(priority). -export([main/0]). main() -> self() ! {job, low}, self() ! {job, high}, A = receive {job, high} -> high_done end, B = receive {job, low} -> low_done end, io:format("~p~n", [A]), io:format("~p~n", [B]).

erlc priority.erl

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

high_done low_done

A pattern may bind a variable and guard it: {job, Id} when Id > 10 -> .... A message that fails the guard is skipped like one that fails the pattern, and it stays for a later clause or a later receive.

after 0

after 0 turns a receive into a non-blocking check: it scans the mailbox once and runs the timeout branch if nothing matches. A loop around it drains every matching message and stops at the first empty scan, which is how a process clears its queue before it stops:

drain.erl

-module(drain). -export([main/0, drain/1]). main() -> [self() ! {n, I} || I <- lists:seq(1, 3)], io:format("~p~n", [drain(0)]). drain(Count) -> receive {n, _} -> drain(Count + 1) after 0 -> Count end.

erlc drain.erl

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

3

The list comprehension sends three messages before the receive runs, so all three are there. A message of another shape would stop the count at once, because the pattern does not match it; to drain everything, the pattern is _ and the program has no other use for the mailbox.

A timeout

A positive timeout makes the process wait at most that many milliseconds. A call without one waits forever, which is the wrong default for a client: a server that died before it answered would hang the caller and every process behind it. This program measures the wait with the monotonic clock of the time lesson:

timeout.erl

-module(timeout). -export([main/0]). main() -> Start = erlang:monotonic_time(millisecond), Result = receive never -> arrived after 20 -> timeout end, Elapsed = erlang:monotonic_time(millisecond) - Start, io:format("~p~n", [Result]), io:format("~p~n", [Elapsed >= 20]).

erlc timeout.erl

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

timeout true

The timeout is a lower bound: a loaded machine can make the wait longer, so the check asks Elapsed >= 20 and never compares it to a number it cannot control. The timers lesson uses the same arithmetic for erlang:send_after/3.

What the scan costs

A selective receive scans from the oldest message and stops at the first match. If the match is at the end of a long queue, every receive walks the whole queue, and the process spends its time scanning instead of working. A server that handles a queue of requests with a pattern that only matches some of them, and never removes the others, grows slower with every message it skipped.

The processes in depth lesson reads message_queue_len to see the queue grow; the repair is to match every message a worker can receive, or to split the traffic into different processes so that no mailbox holds two protocols at once.

The catch-all first

A clause whose pattern is a bare variable matches every message, so every clause after it is dead code. The program below receives one message and has one clause, which is fine; the mistake is the same clause placed before the specific ones in a longer receive, where it silently swallows the messages the other clauses were written for:

catch_all.erl

-module(catch_all). -export([main/0]). main() -> self() ! {job, stop}, Result = receive _Any -> other end, io:format("~p~n", [Result]).

erlc catch_all.erl

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

other

The message was a job and the answer says other. In a server the answer would be a reply that names the wrong request, or a shutdown that never runs. Keep the catch-all last, and guard the specific clauses with the tag of the protocol.

Questions

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

  1. How does receive choose a message from the mailbox?

    Answer

    It scans for the first message that matches a clause

    The clauses are patterns, and the runtime takes the oldest message that matches any of them.

  2. What happens to a message that matches no clause of a receive?

    Answer

    It stays in the mailbox for a later receive

    Selective receive leaves the skipped messages in place and in order.

  3. What does after 0 do?

    Answer

    Scans once and runs the timeout branch if nothing matches

    A zero timeout is a non-blocking check of the mailbox.

  4. Why does the timeout program check Elapsed >= 20 instead of Elapsed =:= 20?

    Answer

    A timeout is a lower bound, and a loaded machine waits longer

    The scheduler can delay the process, so the wait is at least the timeout and often a little more.

  5. What does this module print? -module(q1). -export([main/0]). main() -> self() ! low, self() ! high, A = receive high -> high_done end, B = receive low -> low_done end, io:format("~p~n", [A]), io:format("~p~n", [B]).

    Answer

    high_done / low_done

    The first receive skips low and takes high; the next one takes low.

  6. What does this module print? -module(q2). -export([main/0]). main() -> self() ! {n, 1}, self() ! {n, 2}, Count = drain(0), io:format("~p~n", [Count]). drain(N) -> receive {n, _} -> drain(N + 1) after 0 -> N end.

    Answer

    2

    Each matching message increments the count, and the empty scan returns 2.

  7. What does this module print? -module(q3). -export([main/0]). main() -> Result = receive stop -> yes after 5 -> timeout end, io:format("~p~n", [Result]).

    Answer

    timeout

    The mailbox is empty, so the short timeout runs after about five milliseconds.

  8. What does this module print? -module(q4). -export([main/0]). main() -> self() ! {job, stop}, Result = receive _Any -> other end, io:format("~p~n", [Result]).

    Answer

    other

    The bare variable matches the first message, whatever its shape, so the catch-all runs.

  9. Where does a catch-all clause belong in a receive?

    Answer

    Last, after the specific clauses

    A bare pattern matches everything, so any clause after it is unreachable.

  10. What makes a selective receive slow?

    Answer

    A long mailbox with the match at the end

    The scan walks the skipped messages from the oldest, so a long queue is scanned on every receive.

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.

Автор статьи: Arthur Isaev

Изображение баннера