Safe receive in Erlang 20 April 2008
Posted by ojmason in erlang.1 comment so far
I’m currently working on a system which involves a cascade of processes, and ran into some problems with communication between them. Each of the ’service’ processes spends most of the time in a receive loop, and then performs some action. Communication is done via a simple rpc function that sends off a message and then receives the reply and returns.
This is fairly standard, it seems, and is explained in Armstrong’s Programming Erlang (p.145). However, a problem arises if the process (B) sending a message to (C) also receives a request from (A):
A => B <= C
The message from (A) interferes with the response from (C). Chaos ensues.
A possible solution makes rpc more robust, but has a little overhead: any replies sent include the process id of the replying process. The rpc function can then just react to messages coming from the process it called.
This could look like:
rpc(Pid, Msg, Arg) ->
Pid ! {self(), Msg, Arg},
receive
{Pid, Reply} ->
Reply
end.
Problem solved!