Last active
August 29, 2015 14:05
-
-
Save jepio/b96f16b6efda7b95b206 to your computer and use it in GitHub Desktop.
A process chain that sends a message back to starting process.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(ring). | |
-export([start/2, listen/1]). | |
%% listen to pings and forward to Pid | |
listen(Pid) -> | |
receive | |
ping -> | |
Pid ! ping, | |
listen(Pid) | |
end. | |
%% listen to pings for Ctr iterations, sending a status report | |
%% to Self on every iteration and forwarding ping to Pid | |
listen_and_track(_, _, 0) -> ok; | |
listen_and_track(Self, Pid, Ctr) -> | |
receive | |
ping -> | |
Self ! {time, now(), Ctr}, | |
Pid ! ping, | |
listen_and_track(Self, Pid, Ctr - 1) | |
end. | |
%% start a ring that sends a message in circles | |
start(Links, Ctr) -> | |
Self = self(), | |
First = spawn(fun () -> | |
Last = lists:foldl( | |
fun (_X, Pid) -> | |
spawn_link(?MODULE, listen, [Pid]) | |
end, | |
self(), lists:seq(1, Links)), | |
listen_and_track(Self, Last, Ctr) | |
end), | |
Start = now(), | |
First ! ping, | |
measure(Start). | |
%% measure time between two status reports | |
measure(Last) -> | |
receive | |
{time, Time, Ctr} -> | |
io:format("Iteration ~p: ~p us ~n", | |
[Ctr, timer:now_diff(Time, Last)]), | |
measure(Time) | |
after | |
5000 -> | |
io:format("Did not receive more messages, finishing~n"), | |
ok | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment