Skip to content

Instantly share code, notes, and snippets.

@GeertVL-zz
Created July 5, 2012 13:55
Show Gist options
  • Save GeertVL-zz/3053799 to your computer and use it in GitHub Desktop.
Save GeertVL-zz/3053799 to your computer and use it in GitHub Desktop.
Erlang 8.11.2.3 (not refactored)
-module(ring2).
-export([start/2]).
start(Msg,Max) ->
Pid1 = clasp(Max),
Pid2 = ring(),
Pid3 = ring(),
Pid4 = ring(),
shackle(Pid1, Pid2),
shackle(Pid2, Pid3),
shackle(Pid3, Pid4),
shackle(Pid4, Pid1),
send(Pid2, Msg).
shackle(LPid, RPid) ->
LPid ! {connect, LPid, RPid}.
clasp(Max) ->
spawn(fun() -> loop(0,0,1,Max) end).
ring() ->
spawn(fun() -> loop(0,0,0,0) end).
send(StartPid, Msg) ->
StartPid ! {send, Msg}.
loop(LPid, RPid, Beacon, Max) ->
receive
{connect, Left, Right} ->
io:format("shackle connected~n"),
loop(Left, Right, Beacon, Max);
{send, Msg} when (Beacon > 0) and (Beacon < Max) ->
io:format("Message passed clasp: ~p~n", [Msg]),
RPid ! {send, Msg},
loop(LPid, RPid, Beacon + 1, Max);
{send, Msg} when Beacon =:= 0 ->
io:format("Message sent: ~p~n", [Msg]),
RPid ! {send, Msg},
loop(LPid, RPid, Beacon, Max);
{send, Msg} when Beacon =:= 5 ->
io:format("Ring round done.~p~n", [Msg])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment