Skip to content

Instantly share code, notes, and snippets.

@cqfd
Created July 20, 2012 16:07
Show Gist options
  • Save cqfd/3151590 to your computer and use it in GitHub Desktop.
Save cqfd/3151590 to your computer and use it in GitHub Desktop.
Grow your own Erlang process ring
-module(ring).
-export([chain/0, chain/1, start/3]).
chain() ->
chain(self()).
chain(Neighbor) ->
receive
stop ->
io:format("stopping ~p...~n", [self()]),
Neighbor ! stop;
grow ->
NewNeighbor = spawn(ring, chain, [Neighbor]),
io:format("grew ~p~n", [NewNeighbor]),
chain(NewNeighbor);
{send, Msg} ->
Neighbor ! {message, Msg, self()},
chain(Neighbor);
{message, Msg, Origination} ->
case self() of
Origination ->
io:format("message made it back to origination~n"),
chain(Neighbor);
_ ->
io:format("forwarding message: ~p~n", [Msg]),
Neighbor ! {message, Msg, Origination},
chain(Neighbor)
end
end.
sendMany(0, _, _) -> ok;
sendMany(N, Msg, Pid) ->
Pid ! Msg,
sendMany(N - 1, Msg, Pid).
start(M, N, Msg) ->
Pid = spawn(ring, chain, []),
sendMany(N, grow, Pid),
sendMany(M, {send, Msg}, Pid).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment