關(guān)于receive的理解,總算理解到了,相關(guān)見erlang面試題中receive的理解。
下面給出三個(gè)例子
第一個(gè)例子來實(shí)現(xiàn):
- 清空郵箱一個(gè)消息
- 清空郵箱一個(gè)指定消息
- 清空郵箱所有消息
來證明
- receive 只會(huì)遍歷郵箱一次;下一次遍歷,是在受到新消息的時(shí)候
- 遍歷郵箱的時(shí)候,匹配到一個(gè),立刻結(jié)束匹配的過程,不回繼續(xù)進(jìn)行
- 不加after語句的話,receive 遍歷郵箱完畢,如果沒有匹配到,就會(huì)阻塞在receive這里;如果匹配到了,就會(huì)執(zhí)行receive end后面的代碼塊;
第二個(gè)例子是實(shí)現(xiàn)消息先后順序接受的實(shí)現(xiàn),即:
只能處理消息'a'后,才能開始處理消息'b';
如果消息'b'先到,那么不會(huì)處理
第三個(gè)例子是實(shí)現(xiàn)消息的優(yōu)先級(jí)的接受,來自
《learn you some erlang for great good》
例子1:
%%%-------------------------------------------------------------------
%%% @author mohe
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 02. 九月 2016 下午3:07
%%%-------------------------------------------------------------------
-module(test).
-author("mohe").
%% API
-compile(export_all).
init() -> %%初始化
Pid = spawn(fun() -> loop() end),
register(test, Pid).
loop() -> %%主循環(huán)
io:format("loop in"),
receive
ok ->
io:format("receive ok,begin process"),
io:format("receive ok,begin end"),
loop();
'flush' ->
flush(),
loop();
{'flush', Msg} ->
flush(Msg),
loop();
'flush_all' ->
flush_all()
end.
flush() -> %%清除一個(gè)消息
receive
Msg ->
io:format("flush:~p", [Msg])
after 0 ->
ok
end.
flush(Msg) -> %%清除一個(gè)指定消息
receive
Msg ->
io:format("flush:~p", [Msg])
after 0 ->
ok
end.
flush_all() -> %%清除所有的消息
receive
Msg ->
io:format("flush:~p", [Msg]),
flush_all()
after 0 ->
ok
end.
運(yùn)行過程
<pre>
test:init(). //初始化
test!ok1. //發(fā)送'ok1'消息
test!ok2. //發(fā)送'ok2'消息
test!ok3. //發(fā)送'ok3'消息
test!ok1. //發(fā)送'ok1'消息
erlang:process_info(whereis(test),messages). //查看郵箱結(jié)果,結(jié)果為:{messages,[ok1,ok2,ok3,ok1]}
//清空郵箱一個(gè)消息
test!flush.
erlang:process_info(whereis(test),messages). //查看郵箱結(jié)果,結(jié)果為:{messages,[ok2,ok3,ok1]},
證明郵箱消息順序是按序到達(dá)的
// 清空郵箱指定消息
test!ok1. //發(fā)送'ok1'消息
erlang:process_info(whereis(test),messages).
{messages,[ok2,ok3,ok1,ok1]}
test!{flush,'ok1'}.
erlang:process_info(whereis(test),messages).
{messages,[ok2,ok3,ok1]
說明只會(huì)遇到匹配成功后,立刻停止匹配過程,
因?yàn)槠ヅ淝坝袃蓚€(gè)'ok1',匹配后,還剩下一個(gè)'ok1'
</pre>
例子2
receive
'a' ->
io:format("receive and process msg:~")
receive
'b' ->
io:format("receive and process msg:~")
end
end.
例子3
-module(multiproc).
important() ->
receive
{Priority, Message} when Priority > 10 ->
[Message | important()]
after 0 ->
normal()
end.
normal() ->
receive
{_, Message} ->
[Message | normal()]
after 0 ->
[]
end.