M是消息传递数目,N进程数量,Msg是传递的消息
-module(exe3_2).
-export([start/3,stop/0]).
start(M,N,Msg) ->register(ring,spawn(fun()->ring_service(M,N,Msg) end)).
stop() -> ring!stop.
ring_service(M,N,Msg) ->
Ring=ring_node(N,[]),%Ring是进程环
send_msg(M,Msg,Ring),
receive
stop -> stop_ring(Ring)
end.
stop_ring([]) ->ok;
stop_ring([H|T]) ->H!stop,
stop_ring(T).
send_msg(0,_Msg,_Ring) ->ok;
send_msg(M,Msg,[H|T]) ->H ! {msg,M,Msg},
send_msg(M-1,Msg,T ++ [H]).
ring_node(N,Ring) when N>0
->Next_Pid = spawn(fun() ->loop() end),
ring_node(N-1,[Next_Pid|Ring]);
ring_node(0,Ring) ->lists:reverse(Ring).
loop() ->
receive
{msg,M,Msg} ->
io:format("~w:~w:~w~n",[self(),M,Msg]),
loop();
stop ->true
end.
原文地址:http://blog.csdn.net/li8630/article/details/44916165