Created
December 3, 2012 13:53
-
-
Save greggy/4195182 to your computer and use it in GitHub Desktop.
This file contains 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
%%%------------------------------------------------------------------- | |
%%% @author greg <> | |
%%% @copyright (C) 2012, greg | |
%%% @doc | |
%%% | |
%%% @end | |
%%% Created : 29 Nov 2012 by greg <> | |
%%%------------------------------------------------------------------- | |
-module(ring). | |
%% API | |
-export([start/3, print/2, loop/1, loop_start/1]). | |
-record(state, { | |
num_procs | |
, msg_num | |
, msg | |
, proc_num=1 | |
, pid | |
, first_pid=0 | |
}). | |
%%%=================================================================== | |
%%% API | |
%%%=================================================================== | |
%%-------------------------------------------------------------------- | |
%% @doc | |
%% @spec | |
%% @end | |
%%-------------------------------------------------------------------- | |
start(ProcNum, MsgNum, Message) -> | |
register(loop_start, spawn(ring, loop_start, [#state{num_procs=ProcNum, msg_num=MsgNum, msg=Message}])), | |
loop_start ! start. | |
%%%=================================================================== | |
%%% Internal functions | |
%%%=================================================================== | |
loop_start(#state{num_procs=ProcNum}=State) -> | |
receive | |
start -> | |
F = fun(#state{proc_num=Num, pid=Pid}=NewState) -> | |
case Num of | |
2 -> | |
spawn(ring, loop, [NewState#state{proc_num=Num, pid=Pid, first_pid=Pid}]); | |
_ -> | |
spawn(ring, loop, [NewState#state{proc_num=Num, pid=Pid}]) | |
end | |
end, | |
[F(State#state{proc_num=N}) || N <- lists:seq(1, ProcNum)], | |
stop | |
end. | |
loop(#state{proc_num=Num, pid=Pid, msg=Msg}=State) -> | |
Pid ! {msg, Msg}, | |
receive | |
stop -> | |
stop; | |
{msg, Message} -> | |
print(Num, Message), | |
loop(State) | |
end. | |
print(Num, Msg) -> | |
lists:flatten(io_lib:format("Process: ~p recieved: ~p~n", [Num, Msg])). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment