Skip to content

Instantly share code, notes, and snippets.

@julianwachholz
Created May 30, 2014 09:40
Show Gist options
  • Save julianwachholz/bc886f383b9c78f93e80 to your computer and use it in GitHub Desktop.
Save julianwachholz/bc886f383b9c78f93e80 to your computer and use it in GitHub Desktop.
%% Erlang Programming, exercise 4-2
%%
%% A variant where the message is passed M times around.
%%
-module (ring).
-compile(export_all).
%% N processes in a ring pass around Message a total of M times.
start(N, Message, M) ->
UnlinkedRing = start_proc([], N),
Ring = lists:append(UnlinkedRing, hd(UnlinkedRing)),
io:format("Ring: ~p~n", [Ring]),
case whereis(msg_proc) of
undefined -> register(msg_proc, spawn(ring, message_proc, [Ring]));
_ -> ok
end,
msg_proc ! {message, {M, Message}},
ok.
start_proc(Pids, 0) ->
Pids;
start_proc(Pids, N) ->
start_proc([spawn(ring, loop, []) | Pids], N - 1).
message_proc([RingHead|Ring]) ->
receive
{message, Message} ->
RingHead ! {Message, Ring},
message_proc([RingHead|Ring]);
stop ->
RingHead ! {stop, Ring},
ok
end.
loop() ->
receive
{stop, [Next|Pids]} ->
io:format("Pid ~p stopped.~n", [self()]),
Next ! {stop, Pids};
{{0, _}, _} ->
io:format("=== Done passing message ===~n", []),
msg_proc ! stop,
loop();
{{M, Message}, [Next|Pids]} ->
io:format("Pid ~p got message ~p~n", [self(), Message]),
Next ! {{M, Message}, Pids},
loop();
{{M, Message}, _Last} ->
io:format("Pid ~p got message ~p~n", [self(), Message]),
msg_proc ! {message, {M - 1, Message}},
loop()
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment