Skip to content

Instantly share code, notes, and snippets.

@lest
Created March 12, 2010 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lest/330704 to your computer and use it in GitHub Desktop.
Save lest/330704 to your computer and use it in GitHub Desktop.
%% 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