Message protocols
Two processes that exchange more than one message need an agreement: what a request looks like, where the answer goes and how long the caller waits. In Erlang that agreement is a small protocol of tagged tuples, and OTP writes it once as gen_server:call/2. This lesson builds the same shape from primitive messages, so the library call is no longer magic.
A request and a reply
A request carries the pid of the sender, a reference and the arguments. The server answers with the same reference, and the caller matches the reference before it reads the value. The reference is the correlation id that makes a reply belong to a request:
call.erl
-module(call). -export([main/0]). server() -> receive {request, From, Ref, N} -> From ! {reply, Ref, N * 2}, server() end. call(Pid, N) -> Ref = make_ref(), Pid ! {request, self(), Ref, N}, receive {reply, Ref, Result} -> {ok, Result} after 100 -> {error, timeout} end. main() -> Pid = spawn(fun server/0), Silent = spawn(fun() -> receive _ -> ok end end), io:format("~p~n", [call(Pid, 21)]), io:format("~p~n", [call(Pid, 1)]), io:format("~p~n", [call(Silent, 1)]).
erlc call.erl
erl -noshell -eval 'call:main(), halt().'
{ok,42} {ok,2} {error,timeout}
The third call reaches a process that takes the request and never answers; the timeout turns that into {error, timeout} instead of a caller that waits forever. The server is a loop, and its state would be an argument of the recursive call; the GenServer lesson replaces the loop with the behaviour that does the same thing.
The reference
A reference is a value that is unique in the node and in the cluster. It is what lets a caller reject a reply from an earlier request that arrived late. Here two replies wait in the mailbox and the caller asks for the newer one; the older stays:
stale_reply.erl
-module(stale_reply). -export([main/0]). main() -> RefOld = make_ref(), RefNew = make_ref(), self() ! {reply, RefOld, old}, self() ! {reply, RefNew, new}, Result = receive {reply, RefNew, Value} -> Value end, io:format("~p~n", [Result]).
erlc stale_reply.erl
erl -noshell -eval 'stale_reply:main(), halt().'
new
Without the reference, the first receive would take the old reply, and the caller would act on an answer to a question it already abandoned. The reference is also the key of a monitor: a caller that monitors the server can match a DOWN against the same operation and answer {error, {server_down, Reason}} at once.
The timeout and the dead server
A timeout protects the caller from a server that is busy; a monitor protects it from a
server that died. Both belong in a real call. A caller that waits without either is tied
to the health of another process, and a chain of such callers is how one crash becomes
an outage.
The OTP call wraps both: gen_server:call(Server, Request, Timeout)
sends the request, monitors the server and answers
{error, timeout} or an exit when the server dies. A protocol of
your own should copy that shape rather than invent a third one.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What three values does a request carry in the lesson?
Answer
The sender, a reference, and the arguments
The server needs to know where to reply and which request the reply belongs to.
-
What is
make_ref/0for?Answer
It creates a unique reference to correlate a reply
The reference is unique, so a reply can be matched to the request that caused it.
-
What does a caller do when the reply does not arrive in time?
Answer
Returns a timeout error and stays alive
The
afterbranch turns the wait into a value, and the caller decides what to do next. -
What adds the monitor to an OTP call?
Answer
The call monitors the server and reports its death
gen_server:callwatches the server so a death becomes an immediate error, not a wait. -
What does this module print?
-module(q1). -export([main/0]). main() -> A = spawn(fun() -> receive {ask, From, Ref, N} -> From ! {answer, Ref, N + 1} end end), Ref = make_ref(), A ! {ask, self(), Ref, 41}, receive {answer, Ref, Value} -> io:format("~p~n", [Value]) after 100 -> io:format("timeout~n") end.Answer
42The server adds one and replies with the same reference, so the caller reads 42.
-
What does this module print?
-module(q2). -export([main/0]). main() -> R1 = make_ref(), R2 = make_ref(), self() ! {reply, R1, old}, self() ! {reply, R2, new}, receive {reply, R2, Value} -> io:format("~p~n", [Value]) end.Answer
newThe receive matches the second reference and skips the older reply.
-
What does this module print?
-module(q3). -export([main/0]). main() -> Silent = spawn(fun() -> receive _ -> ok end end), Ref = make_ref(), Silent ! {ask, self(), Ref}, receive {answer, Ref, _} -> answer after 10 -> io:format("timeout~n") end.Answer
timeoutThe silent process never replies, so the short timeout branch runs.
-
What does this module print?
-module(q4). -export([main/0]). main() -> Ref = make_ref(), self() ! {reply, Ref, alpha}, self() ! {reply, Ref, beta}, A = receive {reply, Ref, Value} -> Value end, B = receive {reply, Ref, Value2} -> Value2 end, io:format("~p~n", [A]), io:format("~p~n", [B]).Answer
alpha/betaBoth replies carry the same reference, so the receives take them in mailbox order.
-
Why does a reference beat a request number such as an integer?
Answer
It is unique without a shared counter or a lock
The runtime creates a unique value for every call, with no coordination between processes.
-
Which OTP function already implements this protocol?
Answer
gen_server:call/3gen_server:call/3sends the request, correlates the reply, monitors the server and applies the timeout.
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