Created
March 12, 2010 19:48
-
-
Save lest/330704 to your computer and use it in GitHub Desktop.
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
%% Create N processes in a ring. | |
%% Send a message round the ring M times so that a total of N * M messages get sent. | |
-module(ring). | |
-export([start/0, start/2]). | |
start() -> | |
start(10, 10). | |
start(N, M) -> | |
start_child(N - 1, M, [self()]). | |
start_child(0, M, Pids) -> | |
[LastPid|_Pids] = Pids, | |
io:format("last pid ~p~n", [LastPid]), | |
io:format("counting ~p~n", [M]), | |
loop_first(M, LastPid); | |
start_child(N, M, Pids) -> | |
[PrevPid|_Pids] = Pids, | |
io:format("starting ~p with prev ~p~n", [N + 1, PrevPid]), | |
Pid = spawn(fun() -> loop(N, PrevPid) end), | |
start_child(N - 1, M, [Pid|Pids]). | |
loop_first(0, _Pid) -> | |
io:format("done~n"); | |
loop_first(M, Pid) -> | |
Pid ! {next, M}, | |
receive | |
{next, M} -> | |
io:format("counting ~p~n", [M - 1]), | |
loop_first(M - 1, Pid) | |
end. | |
loop(N, PrevPid) -> | |
receive | |
{next, M} -> | |
io:format("forward on #~p~n", [N + 1]), | |
PrevPid ! {next, M}, | |
loop(N, PrevPid) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment