Created
July 20, 2009 17:42
-
-
Save zakovyrya/150468 to your computer and use it in GitHub Desktop.
USAGE: ring:start(M,N,Msg).<br/>M: times to pass message, N: number of processes in ring, Msg: message
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_node/3, start_node/4]). | |
-export([start/3]). | |
start(M, N, Msg) when (M>0) and (N>0) -> spawn(?MODULE, start_node, [M, N, Msg]). | |
start_node(M, N, Msg) -> | |
NextPid = spawn(?MODULE, start_node, [M, N-1, Msg, self()]), | |
io:format("DEBUG: started first node. pid: ~p, npid: ~p, N: ~p~n", [self(), NextPid, N]), | |
loop(NextPid). | |
start_node(M, 1, Msg, FirstPid) -> | |
io:format("DEBUG: started last node. pid: ~p, fpid: ~p~n", [self(), FirstPid]), | |
FirstPid ! {msg, Msg}, | |
io:format("DEBUG: sent first message to ~p~n", [FirstPid]), | |
loop(M, FirstPid); | |
start_node(M, N, Msg, FirstPid) -> | |
NextPid = spawn(?MODULE, start_node, [M, N-1, Msg, FirstPid]), | |
io:format("DEBUG: started middle node. pid: ~p, npid: ~p, N: ~p~n", [self(), NextPid, N]), | |
loop(NextPid). | |
loop(1, FirstPid) -> | |
receive | |
{msg, _Msg} -> | |
io:format("DEBUG: last node ~p received last message~n", [self()]), | |
io:format("DEBUG: ~p terminating ring~n", [self()]), | |
FirstPid ! quit, | |
loop(FirstPid) | |
end; | |
loop(M, FirstPid) -> | |
receive | |
{msg, Msg} -> | |
io:format("DEBUG: last node ~p received message~n", [self()]), | |
io:format("DEBUG: passing message one more time. M: ~p~n", [M]), | |
FirstPid ! {msg, Msg}, | |
loop(M-1, FirstPid) | |
end. | |
loop(NextPid) -> | |
receive | |
quit -> | |
NextPid ! quit, | |
io:format("DEBUG: ~p quitting~n", [self()]); | |
{msg, Msg} -> | |
io:format("DEBUG: ~p received message~n", [self()]), | |
NextPid ! {msg, Msg}, | |
io:format("DEBUG: ~p passed message to ~p~n", [self(), NextPid]), | |
loop(NextPid) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment