Created
December 22, 2011 18:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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