Selecting messages needed by the current step

A process can receive several kinds of messages while its current state permits handling only some. Selective receive expresses the needed conditions as patterns and leaves other messages for later processing.

Erlang receive searches from the queue’s start for the first message matching an arm’s pattern and guard, testing arms in source order for each message. It removes the selected message while leaving others unchanged, and can suspend when none matches.

References: [1]

Processing order can differ from arrival order

A later matching message can be processed before an earlier nonmatching one. This allows waiting for a particular reply, but requires a policy for old messages; leaving them pending does not make them disappear.

Queue placement itself has conditions. Erlang normally enqueues in reception order, with different rules when priority-message reception is enabled. Signal delivery, queue ordering, and receive selection are related but distinct orderings.

References: [1] [2]

A short timeout need not avoid scanning

Erlang documents a cost proportional to the messages preceding a match. Even receive with after 0 can inspect the whole queue before concluding that no message matches, so zero waiting does not imply constant computational cost.

Certain patterns using a freshly created reference permit compiler and runtime optimizations that narrow the inspected range. These depend on specific conditions. Managing irrelevant messages, request identity, and backlog remains necessary rather than merely shortening timeouts.

References: [1]