Skip to content

Instantly share code, notes, and snippets.

@jaeyson
Created October 3, 2022 08:59
Show Gist options
  • Save jaeyson/8a2e9371e9ec23ab50f1a89cf29a0d71 to your computer and use it in GitHub Desktop.
Save jaeyson/8a2e9371e9ec23ab50f1a89cf29a0d71 to your computer and use it in GitHub Desktop.
-module(ring).
-export([start/0]).
% start/0 top function to run.
% c(ring).
% ring:start().
start() ->
% trace who (process) called the func (mod:func)
dbg:tracer(),
dbg:p(all, c),
dbg:tpl(?MODULE, x),
run_ring(3, 2).
run_ring(RingSize, MsgRepeatCount) ->
start_ring_element(self(), RingSize, MsgRepeatCount).
start_ring_element(StartRingPid, 1, MsgRepeatCount) ->
StartRingPid ! {self(), StartRingPid},
ring_last_element(StartRingPid, MsgRepeatCount);
start_ring_element(StartRingPid, NumberOfRingElemetsLeft, MsgRepeatCount) ->
NextPid = spawn(fun() -> start_ring_element(StartRingPid, NumberOfRingElemetsLeft - 1, MsgRepeatCount) end),
ring_element(NextPid).
ring_element(NextPid) ->
receive
stop ->
NextPid ! stop;
{From, To} ->
io:format("Msg from = ~p \t to: ~p\n", [From, To]),
NextPid ! {self(), NextPid},
ring_element(NextPid)
end.
ring_last_element(NextPid, 0) ->
NextPid ! stop;
ring_last_element(NextPid, MsgRepeatCount) ->
receive
stop -> NextPid ! stop;
Msg -> NextPid ! Msg,
ring_last_element(NextPid, MsgRepeatCount - 1)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment