jump to navigation

Safe receive in Erlang 20 April 2008

Posted by Oliver Mason in erlang.

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},
{Pid, Reply} ->

Problem solved!



1. Gleb Peregud - 20 April 2008

Hello. This method is o.k. if you are talking about simple cases with synchronous rpc. If you are talking about complex multi-node and multi-process system with a lot of asynchronous calls (with message routing between processes) it is better to use erlang:make_ref() which generates unique (per node) reference. Hence by using

RpcId = {node(), make_ref()}

you can ensure, that process receives a response to the given request.

You can rewrite your code like this:

rpc(Pid, Msg, Arg) ->
RpcId = {node(), make_ref()},
Pid ! {self(), RpcId, Msg, Arg},
{RpcId, Reply} ->

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: