Skip to content
Erlang

Селективный receive со ссылками

Выбор конкретного ответа из множества сообщений через уникальную ссылку.

#receive#references#rpc

Code

erlang
-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.