Sur la page 158 de Programming Erlang, il y a un exercice. Faire un anneau de N processus. On envoie le message à l’un deux, et le message parcourt l’anneau M fois.
-module (exoc).
-export([start/2]).
start(Max,Tours) ->
start(Max,Max,0, Tours).
start(0, _Max,PrevPid, _Tours)->
PrevPid;
start(Max, Max, _Pid, Tours) ->
F = fun() ->
LastPid = start(Max-1, Max, self(), Tours),
loop(LastPid, Tours)
end,
spawn(F);
start(N, Max,PrevPid,Tours) ->
Pid=spawn(fun() -> loop(PrevPid, Tours) end ),
start(N-1, Max, Pid, Tours).
loop(_ToPid,0) ->
io:format("~nFini pour :~p",[self()]);
loop(ToPid, Tours) ->
receive
M->
ToPid ! M,
io:format("~n(~p) :~p -> ~p.",[self(),M, ToPid]),
loop(ToPid, Tours-1)
end.