Erlang receive代码块

本文深入解析了Erlang编程语言中`receive`代码块的执行流程,详细阐述了如何通过模式匹配从邮件箱中获取并处理消息,包括消息匹配成功后的执行流程、超时处理机制以及消息保存机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

[img]http://dl.iteye.com/upload/attachment/0078/6477/52549fae-2faa-3569-be9e-31a3a34a1aef.jpg[/img]

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代码块的默认操作)

[color=red]-------------------------------------------------------------------------华丽分割线-------------------------------------------------------------------------[/color]

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

[b]receive works as follows:[/b]

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值