[erlang-questions] On selective receive (Re: eep: multiple patterns)

Jay Nelson <>
Sat May 31 20:50:14 CEST 2008

 > I would really like to discourage people from avoiding
 > selective receive because it's "expensive".

I would second that.  Selective receive is similar to thinking
single threaded in a multi-threaded environment (the approach
that erlang in general supports).  Isolate a group of related
messages using the selective part and then you don't have to
worry about all the other interleave interruptions that may occur.

But as Ulf said, we aren't aware of any books on how to structure your
messaging architecture which take you stepwise up from a
simple architecture to a complicated selective receive.  I do
caution a beginner to start simple and build up; understand how
the message queue works by creating test scenarios that produce
specific results.

One of the early admonishments one hears is to always have a
catch all clause in your receive statements, which of course
eliminates selective receive and causes your code to process
messages in the order they arrived.  To get around this, you
can split the receive into separate functions, and then call one
function to handle one logical message stream and another
function to handle a different logical message stream.

The thing to watch out in the split receive case is the missing

    {a, How} -> do_stuff();
    {a, When, Why} -> do_stuff();
after 500 -> timeout

   {b, How} -> do_stuff();
   {b, When, Why} -> do_stuff();
after 500 -> timeout

Now you can handle the two streams independently, maybe
giving more time to 'a' stream items than 'b' stream items.
But suppose you accidentally send a message with {c, X}
and it only happens once an hour.  You will gradually get a
queue which fills up with {c, X} messages, but you won't notice
the slowdown for a few days.

Whenever you have disjoint receive statements, you need to
take care that there is a technique for emptying unexpected
messages.  Even though your queue should never get long,
a new programmer on the staff may send a new message to
your process without you knowing and it will take a while
to discover the cause.


More information about the erlang-questions mailing list