Created
December 10, 2012 11:45
-
-
Save greggy/4250155 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, init/1, print/3, loop/1]). | |
-record(state, { | |
num_procs | |
, msg_num | |
, msg | |
, proc_num=1 | |
, first_pid=0 | |
}). | |
%%%=================================================================== | |
%%% API | |
%%%=================================================================== | |
%%-------------------------------------------------------------------- | |
%% @doc | |
%% @spec | |
%% @end | |
%%-------------------------------------------------------------------- | |
start(ProcNum, MsgNum, Message) -> | |
spawn(ring, init, [#state{num_procs=ProcNum, msg_num=MsgNum, | |
msg=Message}]). | |
init(#state{num_procs=NumProcs, proc_num=Num, first_pid=Pid, | |
msg=Msg, msg_num=NMsg}) when NumProcs == Num -> | |
loop({Num, Pid, Msg, NMsg}); | |
init(#state{proc_num=Num, msg=Msg, msg_num=NMsg}=State) when Num == 1 -> | |
Pid = spawn(ring, init, [State#state{proc_num=Num+1, first_pid=self()}]), | |
loop({Num, Pid, Msg, NMsg}); | |
init(#state{proc_num=Num, msg=Msg, msg_num=NMsg}=State) -> | |
Pid = spawn(ring, init, [State#state{proc_num=Num+1}]), | |
loop({Num, Pid, Msg, NMsg}). | |
%%%=================================================================== | |
%%% Internal functions | |
%%%=================================================================== | |
loop({Num, Pid, Msg, NMsg}) -> | |
timer:sleep(100), | |
[Pid ! {msg, Msg, X} || X <- lists:seq(1, NMsg)], | |
receive | |
{msg, Message, NMsg} -> | |
print(Num, Message, NMsg), | |
stop; | |
{msg, Message, GMsg} -> | |
print(Num, Message, GMsg), | |
loop({Num, Pid, Msg, NMsg}); | |
stop -> | |
stop; | |
_ -> | |
{error, invalid_message} | |
end. | |
print(Num, Msg, NMsg) -> | |
io:format("Process: ~p recieved: ~p times: ~p~n", [Num, Msg, NMsg]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment