Skip to content

Instantly share code, notes, and snippets.

@pperon
Created December 22, 2011 18:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save pperon/1511301 to your computer and use it in GitHub Desktop.
Save pperon/1511301 to your computer and use it in GitHub Desktop.
My solution to the Erlang Process Ring Exercise 4-2 in Programming Erlang
-module(ring).
-export([start/3, loop/0]).
%%%
%%% An implementation of an Erlang process ring. This is probably the
%%% Erlang equivalent of breaking your first board in Karate class.
%%%
start(NumMsgs, NumProcs, Msg) ->
UnlinkedRing = create_process([], NumProcs),
LinkedRing = lists:append(UnlinkedRing, [hd(UnlinkedRing)]),
send_message({Msg, NumMsgs}, LinkedRing).
create_process(Pids, 0) ->
Pids;
create_process(Pids, Count) ->
create_process([spawn(?MODULE, loop, [])|Pids], Count-1).
send_message({_, 0}, [Next|Pids]) ->
Next ! {stop, Pids};
send_message({Msg, NumMsgs}, [Next|Pids]) ->
Next ! {Msg, NumMsgs, Pids},
send_message({Msg, NumMsgs-1}, [Next|Pids]).
loop() ->
receive
{stop, [Next|Pids]} ->
io:format("~p -~p-> ~p~n", [self(), stop, Next]),
Next ! {stop, Pids};
{Msg, NumMsgs, [Next|Pids]} ->
io:format("~p -~p-> ~p~n", [self(), NumMsgs, Next]),
Next ! {Msg, NumMsgs, Pids},
loop()
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment