Selective receive (RE: Structs (was RE: Record selectors))

Sven-Olof Nystr|m <>
Tue Jan 21 13:06:58 CET 2003

Ulf Wiger writes:
 > > > I think a single message queue and pattern matching go well
 > > > in hand with state-oriented programming. Again, the POTS
 > > > example:

 > >Yes. This could be written with a receive operation that
 > >simply grabs the next message in the mailbox + a case
 > >statement.
 > Yes, because the receive statement in this case has a
 > catch-all branch, which means that it will always consume
 > the first message that comes along.
 > The following is a state from a prototype ATM call control
 > state machine:
 > loop_setup_sent(HcData, VolData) ->
 >     receive
 >         {setupB, PidB, MsgType, IEs, HcIdB, ResourcesB} ->
 >             %%from bside
 >             case MsgType of
 >             end;
 >         {from_dispatch, HcIdAfromA, MessageType, Message} ->
 >             %%from sigport (Aside)
 >             case {uniccLibrary:tokenize_sort(Message),
 >                   MessageType} of
 >             end
 >     end
 > This is slightly more difficult to rewrite as a case
 > statement, because the code is doing a blocking wait on two
 > "channels" simultaneously. One may assume that in the normal
 > case, the program will consume the first message on any of
 > the channels which it is currently monitoring. Then, this
 > amounts to a blocking poll() on a subset of open channels
 > followed by a case. I have trouble finding example code
 > where this would not be adequate.

In other words, the multi-channel solution would use two channels, one
from B side and one from A side, and the receiving process would look
for messages on both channels.

 > >Matching receive is a rather strange construct. If
 > >arbitrary expressions were allowed in guards, it would be
 > >possible to write a receive that counted the messages in a
 > >mailbox. Unlike case statements, there is no way to
 > >translate a receive into simpler things (this affected the
 > >design of Core Erlang). As far as I know, no other
 > >programming language has anything similar.
 > This need not be an argument against matchin receive per se,
 > as few other languages have a track record in concurrent
 > programming that matches that of Erlang... (:

No, not necessarily. On the other hand, I suppose it would be
interesting for future language designers to learn _why_ Erlang is the
best concurrent language available. Is it because of matching receive
or something else?

 > But I cannot argue that matching receive is indispensable as
 > long as I cannot find a single good example where one
 > couldn't do equally well (more or less) with multiple
 > channels. (:

Sven-Olof Nyström

More information about the erlang-questions mailing list