Selective Receive with References
Match a specific reply out of many messages using a unique reference.
Code
-module(rpc).
-export([call/2]).
call(Server, Request) ->
Ref = make_ref(), % unique reference
Server ! {call, Ref, self(), Request},
receive
{Ref, Reply} -> Reply % only matches our reply
after 5000 ->
exit(timeout)
end.
% Server side (typically in a gen_server handle_call):
% handle_call(Request, {FromPid, Ref}, State) ->
% Reply = ...,
% FromPid ! {Ref, Reply},
% {noreply, State}.
% The Ref makes the receive selective — even if the mailbox contains
% dozens of unrelated messages, receive skips them and matches only
% the one tagged with our Ref. Stale messages stay in the mailbox
% until a later receive handles them.Explanation
make_ref/0 returns a globally-unique reference. Tagging a request with it lets the caller's receive match only the corresponding reply, even when the mailbox holds other traffic. This is the building block of every synchronous RPC in Erlang, including gen_server:call. The downside of selective receive is that non-matching messages accumulate and slow future scans — gen_server avoids this by handling every message in order.
More Erlang Snippets
Ping-Pong Processes
Two processes pass messages back and forth using spawn and receive.
gen_server Counter
Build a stateful server with the gen_server behaviour.
Supervisor Tree
Define a supervisor that starts workers and restarts them on crash.
Links, Exit Trapping & 'Let It Crash'
Use link and trap_exit to detect process death and recover.
Stateful Server via Tail Recursion
Hold mutable state in a process by threading it through recursive calls.
Parallel Map with rpc:pmap
Apply a function to each list element in parallel across processes.