[erlang-questions] [LONG] How to make synchronous message passing

Richard Carlsson <>
Wed Oct 3 09:27:13 CEST 2007

ZeD wrote:
> if a process P want to make a synchronous call to Q, then it send a message 
> and waits for a reply.
> What's appened when another process, R (just for make and example) send a
> message to P 'before' the Q reply?

Then, the message from R will be before the reply from Q in the mailbox
of P. But if you use selective matching, as in synchro2, then P can
ignore the message from R and accept only the message from Q.

> In particular, what if Q first send another message to P, then waits for the
> reply, and only after all this, send the reply to the original message to
> P?

If P is in synchro2, and Q sends another message to P (not the reply),
then either P will mistakenly think that it is the reply (if it can have
the same form as a reply), or P will just ignore the message (like it
ignored the message from R) and keep waiting for the reply. This is
the whole point: if the communication is _synchronous_, then P will not
do anything at all (per definition) until it gets the reply. Other
messages will be queued up in the mailbox.

> Oh, and just to know, let's say P was described by the function f(), which
> have a receive; now P want to talk to Q, then now the behavior of P is
> described by synchro2(), wich also have a receive. Let's say P finally had
> a reply, so the control came back to f(). What append to messages not
> matched by synchro2()? they became automatically "receveived" by f()? They
> get lost?

No. The process P has a mailbox (a queue), and when the receive-
expression in synchro2 finishes, it will only remove the matched
message. All other messages remain in the queue. Nothing is lost
unless you throw it away yourself.


More information about the erlang-questions mailing list