Selective Receive
The receive
primitive is used to extract messages from
the process mailbox, but it does more than simple pattern matching;
it also queues unmatched messages for later processing and manages timeouts.
The following statement:
| receive |
| Pattern1 [when Guard1] -> |
| Expressions1; |
| Pattern2 [when Guard2] -> |
| Expressions2; |
| ... |
| after |
| Time -> |
| ExpressionsTimeout |
| end |
works as follows:
-
When we enter a receive statement, we start a timer (but only if an after section is present in the expression).
-
Take the first message in the mailbox and try to match it against
Pattern1
,Pattern2
, and so on. If the match succeeds, the message is removed from the mailbox, and the expressions following the pattern are evaluated.
Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.