Skip to content

Instantly share code, notes, and snippets.

@tarnacious
Created March 14, 2011 07:13
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 tarnacious/868867 to your computer and use it in GitHub Desktop.
Save tarnacious/868867 to your computer and use it in GitHub Desktop.
Erlang implementation of a circular message chain of n nodes, which pass a message around m times. I wrote this over a year ago, so go easy please!
-module(messagechain).
-compile(export_all).
start() ->
Pid = messagechain:setup(3, 3),
Pid ! { message }.
setup(Times, Loops) ->
Pid = spawn(fun() -> message_node(Loops) end),
EndPid = messagechain:create_nodes(Times, Loops, Pid),
Pid ! {sendto, EndPid},
Pid.
create_nodes(0, _, Pid) -> Pid;
create_nodes(Times, Loops, Pid) ->
PidNew = spawn(fun() -> message_node(Pid, Loops) end),
io:format("Spawn: ~p ~p ~n", [Pid, PidNew]),
messagechain:create_nodes(Times-1, Loops, PidNew).
message_node(Loops) ->
receive
{sendto, Pid} ->
io:format("Linking ~p to ~p ~n", [Pid, self()]),
message_node(Pid, Loops)
end.
message_node(Pid, 0) ->
io:format("Done: ~p~n", [self()]);
message_node(NextPid, Loops) ->
receive
Any ->
io:format("Received: ~p (~p)~n", [self(), Loops]),
NextPid ! Any,
message_node(NextPid, Loops - 1)
end.
$ erl -pa messagechain.erl
Erlang R13B03 (erts-5.7.4) [source] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.4 (abort with ^G)
1> messagechain:start().
Spawn: <0.37.0> <0.38.0>
Spawn: <0.38.0> <0.39.0>
Spawn: <0.39.0> <0.40.0>
Linking <0.40.0> to <0.37.0>
{message}
Received: <0.37.0> (3)
Received: <0.40.0> (3)
Received: <0.39.0> (3)
Received: <0.38.0> (3)
Received: <0.37.0> (2)
Received: <0.40.0> (2)
Received: <0.39.0> (2)
Received: <0.38.0> (2)
Received: <0.37.0> (1)
Done: <0.37.0>
Received: <0.40.0> (1)
Done: <0.40.0>
Received: <0.39.0> (1)
Done: <0.39.0>
Received: <0.38.0> (1)
Done: <0.38.0>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment