[erlang-questions] Can Erlang messages be delivered out of order?

Johnny Billquist bqt@REDACTED
Sun Jan 25 04:06:37 CET 2009

Sergey S wrote:
> Hello.
> Does Erlang runtime guarantee that messages will be delivered in
> exactly the same order as they were sent?
> To illustrate my question I've written a simple example:
> %-------------
> process_flag(trap_exit, true),
> Parent = self(),
> spawn_link(fun() ->
>                          Parent ! hello,
>                          Parent ! world
>                  end)
> receive hello -> ok end,
> receive world -> ok end,
> receive {'EXIT', _Pid, normal} -> ok end.
> %-------------
> Is it guaranteed by the runtime that the 'hello' message will always
> be the first message put into mailbox, 'world' - the second one, and
> {'EXIT', _Pid, normal} - third?

If you read the manual, you'll find that each process have it's own 
receive queue, and that new messages are always placed at the end of 
that queue.
So, for you example, yes. The messages will be in the order you expect.
It always becomes more interesting when you have several processes doing 
sends to the same target process, since then it's impossible to tell 
which message will be first in the queue in that case, but that should 
be pretty obvious. :-)

However, your example program don't work the way you seem to expect 
anyway. The receive function isn't actually extracting the first message 
in the receive queue, but the first *matching* message.
So, even if the messages would have been pleced in the wrong order, your 
program would have worked just as fine.


More information about the erlang-questions mailing list