Labels

Sunday, May 3, 2009

Programming Erlang - Exercise 8.11.2 NV Code

(NV algorithm)
-module(c8p2_t).
-export([start/2]).
start(Rounds, Size) ->
Ring = ring(Size-1, self()), %% Set up a ring of Size-1, because self() will participate.
statistics(wall_clock),
Ring ! {ping, Rounds}, %% Send the ping into the ring.
main(Ring), %% Put myself into the ring.
{_, Elapsed} = statistics(wall_clock),
io:format("Rounds: ~p / Ring size: ~p. Ringing ~p messages took ~p seconds~n", [Rounds,Size,Rounds * Size, Elapsed/1000]),
io:format("Avg ping message elapsed time: ~p miliseconds.~n", [Elapsed/(Rounds*Size)]).

%% Create a ring of specified size. Boss is the start of the ring.
ring(1, Boss) ->
spawn(fun() -> proc(1, Boss) end);
ring(N, Boss) ->
spawn(fun() -> proc(N, ring(N-1, Boss)) end).

%% Proc is a process in the ring. N is its number in the ring, Next is the next process.
proc(N, Next) ->
receive {ping, M} -> %% M is the message number.
Next ! {ping, M}, %% Propagate the message.
if
M > 1 -> proc(N, Next); %% Expect more messages.
true -> ready %% We're done.

end
end.

%% Main is similar to proc, but decrements the message number.
%% Returns when all messages have been sent.
main(Next) ->
receive
{ping, M} ->
if
M > 1 ->
Next ! {ping, M-1},
main(Next);
true -> ready
end
end.

No comments:

Post a Comment