Skip to content

Instantly share code, notes, and snippets.

@GeertVL-zz
Created July 5, 2012 14:59
Show Gist options
  • Save GeertVL-zz/3054192 to your computer and use it in GitHub Desktop.
Save GeertVL-zz/3054192 to your computer and use it in GitHub Desktop.
Erlang 8.11.2.3 (refactor round 2)
-module(ring2).
-export([start/3]).
start(Msg,Count,Max) ->
Head = clasp(Max),
connect(Head, Count),
send(Head, Msg).
shackle(LPid, Count) when Count > 1 ->
RPid = spawn(fun() -> loop(0,-1) end),
LPid ! {connect, RPid},
shackle(RPid, Count - 1);
shackle(LPid, Count) when Count =:= 1 ->
RPid = spawn(fun() -> loop(0,-1) end),
LPid ! {connect, RPid},
RPid.
connect(Head, Count) ->
shackle(Head, Count) ! {connect, Head}.
clasp(Max) ->
spawn(fun() -> loop(0,Max) end).
send(StartPid, Msg) ->
StartPid ! {send, Msg}.
loop(RPid, Max) ->
receive
{connect, Right} ->
io:format("shackle connected~n"),
loop(Right, Max);
{send, Msg} when Max > 0 ->
io:format("Message passed clasp: ~p~n", [Msg]),
RPid ! {send, Msg},
loop(RPid, Max - 1);
{send, Msg} when Max =:= -1 ->
io:format("Message sent: ~p~n", [Msg]),
RPid ! {send, Msg},
loop(RPid, Max);
{send, Msg} when Max =:= 0 ->
io:format("Ring round done.~p~n", [Msg])
end.
-module(ring2).
-export([start/3]).
start(Msg,Count,Max) ->
Head = spawn(fun() -> loop(0,Max) end),
close(Head, Count),
send(Head, Msg).
shackle(LPid, Count) when Count > 1 ->
shackle(create(LPid), Count - 1);
shackle(LPid, Count) when Count =:= 1 ->
create(LPid).
create(LPid) ->
RPid = spawn(fun() -> loop(0,-1) end),
LPid ! {connect, RPid},
RPid.
close(Head, Count) ->
shackle(Head, Count) ! {connect, Head}.
send(StartPid, Msg) ->
StartPid ! {send, Msg}.
loop(RPid, Max) ->
receive
{connect, Right} ->
io:format("shackle connected~n"),
loop(Right, Max);
{send, Msg} when Max > 0 ->
io:format("Message passed clasp: ~p~n", [Msg]),
RPid ! {send, Msg},
loop(RPid, Max - 1);
{send, Msg} when Max =:= -1 ->
io:format("Message sent: ~p~n", [Msg]),
RPid ! {send, Msg},
loop(RPid, Max);
{send, Msg} when Max =:= 0 ->
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