Labels

Sunday, May 3, 2009

Programming Erlang - Exercise 8.11.2 MM#2 Code

(MM#2 algorithm)-module(c8p2m_t2).
-export([c8_ping/2,c8_loop/1,c8_cntrl/1
]).

%%-----------------------------* start CREATE the RING *-----------------------------------------------
c8_ping(N,M) when is_integer(N), is_integer(M), N > 1, M > 1 ->
Max = erlang:system_info(process_limit),
StartP = spawn(?MODULE, c8_cntrl, [[self(), M]]), %%--- START process pid of the RING
case (N > Max) of
true ->
EndP = c8_for(2, Max, StartP); %%--- END process pid of the RING
false ->
EndP = c8_for(2, N, StartP) %%--- END process pid of the RING
end,
StartP ! EndP, %%--- Initiate the ping process
io:format(" Max number of processes:~p/Ring size:~p/Number of circles:~p~n", [Max,N,M]),
io:format(" Total message count:~p~n", [N*M]).
%%-----------------------------* end CREATE the RING *-------------------------------------------------

%%-----------------------------* start Regular RING PROCESS *------------------------------------------
c8_loop(NextP)->
receive
{ping,M}->
if
M > 0 ->
NextP ! {ping,M}, %%--- ping the message to the next process!
c8_loop(NextP);
true ->
NextP ! {ping,0} %%--- ping to the next process to die!
end
end.
%%-----------------------------* end Regular RING PROCESS *--------------------------------------------

%%-----------------------------* start Control RING PROCESS *------------------------------------------
c8_cntrl([NextP,M])->
receive
{ping,Cnt} ->
if
Cnt > 0 -> %%--- Start next circle if Cnt > 0!
NextP ! {ping,Cnt-1}, %%--- ping to the next process!
c8_cntrl([NextP,Cnt-1]);
true ->
{_,E_time} = statistics(wall_clock), %%--- calculate ping the ring stats!
io:format(" Total elapsed time: ~p seconds~n", [E_time/1000]),
NextP ! {ping,0} %%--- ping the next process to die!
end;
EndP ->
statistics(wall_clock), %%--- Start elapsed time measurements
EndP ! {ping,M}, %%--- Start the first ping!
c8_cntrl([EndP,M-1]) %%--- FIRST time: close the RING (StartP <-> EndP)!
%% REPLACE Erlang Shell Pid (the start
%% of the ring) served as a placeholder.
end.
%%-----------------------------* end Control RING PROCESS *--------------------------------------------

%%-----------------------------* start HELPER FUNCTIONS *----------------------------------------------
c8_for(N, N, P) -> P;
c8_for(I, N, P) ->
c8_for(I+1, N, spawn(?MODULE, c8_loop, [P])).
%%-----------------------------* end HELPER FUNCTIONS *------------------------------------------------

No comments:

Post a Comment