Skip to content

Instantly share code, notes, and snippets.

@naiquevin
Created May 29, 2014 16:49
Show Gist options
  • Save naiquevin/b5dfa1a0c340682fc24c to your computer and use it in GitHub Desktop.
Save naiquevin/b5dfa1a0c340682fc24c to your computer and use it in GitHub Desktop.
message_ring.erl
-module(message_ring).
-compile(export_all).
-export([]).
%% Problem Statement: Write a ring benchmark. Create N processes in a
%% ring. Send a message round the ring M times so that a total of N *
%% M messages get sent. Time how long this takes for different values
%% of N and M.
-record(state, {index,
next=undefined,
total_procs,
total_msgs,
num_msgs=0}).
start(N, M) ->
State = #state{index=0, total_procs=N, total_msgs=M},
Pid = spawn_link(?MODULE, init, [State]),
register(ringhead, Pid),
Pid.
init(#state{index=Index, total_procs=N}=S) ->
case Index < N of
true ->
% spawn new process
% io:format("spawning next process~n"),
Pid = spawn_link(?MODULE, init, [S#state{index=Index+1, total_procs=N}]),
loop(S#state{next=Pid});
false ->
io:format("linking last element to first to form a ring~n"),
loop(S#state{next=whereis(ringhead)})
end.
loop(#state{next=Next, total_msgs=M, num_msgs=X}=S) ->
receive
{forward, Msg} ->
case X == M of
true ->
io:format("message reached end of the ring~n"),
loop(S);
false ->
%% io:format("~w received message \"~w\", forwarding to ~w~n",
%% [self(), Msg, Next]),
Next ! {forward, Msg},
loop(S#state{num_msgs=X+1})
end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment