Erlang receive代码块

receive代码块是如何执行的呢?

Erlang receive代码块

process会尝试从它的mail-box中循环取出消息进行pattern match:

1.若某一条消息pattern match成功,该条消息将从mail-box中移除并且执行相应的Expression,然后退出receive代码块(先前未匹配的消息,会重新放入mailbox)

2.若没有一条消息能够pattern match成功(或者mail-box中根本没有消息),则process阻塞在receive代码块(等待新消息),若在Time的时间范围内,依然没有消息能够pattern match,就执行超时处理TimeOutExpr,最后退出receive代码块

after 1000:     
表示若在1s中内没有消息能够pattern match ,则进行超时处理
after 0:            
表示若mail-box中没有消息能够pattern match ,则立马进行超时处理
after infinity:
表示若mail-box中没有消息能够pattern match ,则一直阻塞,直到有一条消息能够pattern match(这种情况等价于不写after,是receive代码块的默认操作)

-------------------------------------------------------------------------华丽分割线-------------------------------------------------------------------------

<<Programming Erlang>>相关原文:
receive
     Pattern1 [when Guard1] ->
               Expressions1;
     Pattern2 [when Guard1] ->
               Expressions1;
     ...
after
     Time ->
          ExpressionTimeout
end

receive works as follows:

1. When we enter a receive statement, we start a timer (but only if an after section is present in the expression).

2. 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.

3. If none of the patterns in the receive statement matches the first message in the mailbox, then the first message is removed from the mailbox and put into a “save queue.” The second message in the mailbox is then tried. This procedure is repeated until a matching message is found or until all the messages in the mail-box have been examined.

4. If none of the messages in the mailbox matches, then the process is suspended and will be rescheduled for execution the next time a new message is put in the mailbox. Note that when a new message arrives, the messages in the save queue are not rematched; only the new message is matched.

5. As soon as a message has been matched, then all messages that have been put into the save queue are reentered into the mailbox in the order in which they arrived at the process. If a timer was set, it is cleared.

6. If the timer elapses when we are waiting for a message, then evaluate the expressions ExpressionsTimeout and put any saved messages back into the mailbox in the order in which they arrived at the process.


你可能感兴趣的:(erlang)