Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what order does an Erlang process consume messages?

Tags:

erlang

Are messages processed in a first-come-first-serve basis or are they sorted by timestamp or something like that?

like image 483
Vijay Mathew Avatar asked Jul 28 '11 09:07

Vijay Mathew


1 Answers

Order of messages is preserved between a process and another one. Reading from the FAQ:

10.9 Is the order of message reception guaranteed?

Yes, but only within one process.

If there is a live process and you send it message A and then message B, it's guaranteed that if message B arrived, message A arrived before it.

On the other hand, imagine processes P, Q and R. P sends message A to Q, and then message B to R. There is no guarantee that A arrives before B. (Distributed Erlang would have a pretty tough time if this was required!)

@knutin is right regarding how you can consume messages within a process. As an addition, note that you might use two subsequent receive statements to ensure that a certain message is consumed after another one:

receive
  first ->
    do_first()
end,
receive
  second ->
    do_second()
end

The receive statement is blocking. This will ensure that you never do_second() before you do_first(). The difference from @knutin's second solution is that, in that case, if something not important arrives just before an important one, you queue the important bit.

like image 193
Roberto Aloi Avatar answered Sep 20 '22 05:09

Roberto Aloi