在Erlang User Conference 2006上, 看到一篇關於Erlang message passing的slide, 覺得蠻有趣的
Ref: http://www.duomark.com/erlang/briefings/euc2006/index.html
這篇slide分成3個部份
第1部份是講基本語法
第2部份就是我比較感興趣的地方, 他提到一個有趣的問題
問題描述:
在利用Erlang接受message的時候, 如果有一種priority message, 只要一接收到這種message, 就要先執行相對應的工作, 但是在Erlang的message model中, 他有一個message queue, 所有的message都會被丟到這個queue裡面, 照順序接收,他並不保證有某些message接收的順序是比較高的, 所以我們應該要怎麼解決這個問題?
解法:
其實這個問題並不是很好解決, 他先提出兩種polling的方法, 但是都不是很好, 而且一個process當中最好不要有兩個以上的receive message statement, 可能會有memory performance的問題, 所以他給出利用protocol溝通的方式:
分成router, high process, low process and data store 4個process, 簡單來說router會控制現在是要讓high process還是讓low process去access data store, 所以利用protocol來判斷兩個process當中的message queue, 一旦high process有要處理的message, 就擋掉low process!

第3部份:
介紹一種(event programming) pattern, 來避免利用一大堆State machine來實作(以後更改太困難…).
Description:
central event loop will call associate method according to the message. After the method executed, it will return the control to main loop. The main loop will dispatch messages for multiple process instance which is not blocking! Central event loop can detect asynchronous process message!!
Code:
event_loop(M, S) ->
receive
{From, Event} ->
dispatch(From, Event, M, S);
{From, Ref, Event} ->
dispatch(From, Event, M, S);
Other ->
io:format(”Unknown msg: ~p~n", [Other]),
exit({unknown_msg, Other})
end.
% Recv will be the asynch process id
event_loop(M, S, Recv) ->
receive
{From, Event} when element(From, Recv) == [] ->
dispatch(From, Event, M, S);
{From, Ref, Event} when element(From, Recv) == Ref ->
dispatch(From, Event, M, S);
{From, Ref, Event} when element(From, Recv) == [] ->
dispatch(From, Event, M, S)
end.
% M:Event method can be asynchronous process
% which will return {ok, NewState, Recv}
dispatch(From, Event, M, S) when atom(Event) ->
handle(M:Event(From, S), M);
dispatch(From, {Event, Arg}, M, S) ->
handle(M:Event(From, Arg, S), M).
handle({ok, NewState}, M) ->
event_loop(M, NewState);
handle({ok, NewState, Recv}, M) ->
event_loop(M, NewState, Recv).
Filed under: programming | Tagged: erlang | Leave a comment »