Created
January 23, 2014 13:57
-
-
Save calebsmith/8578779 to your computer and use it in GitHub Desktop.
Simple ping/pong Erlang program
This file contains hidden or 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(ping_module). | |
-export([start/1, ping/2, pong/1, ending_timer/0]). | |
ping(0, Pong_PID) -> | |
Pong_PID ! finished, | |
io:format("ping finished~n", []); | |
ping(N, Pong_PID) -> | |
io:format("Sending ping~n", []), | |
Pong_PID ! {ping, self()}, | |
receive | |
pong -> | |
io:format("Received pong~n", []) | |
end, | |
ping(N - 1, Pong_PID). | |
pong(Timer_PID) -> | |
receive | |
finished -> | |
io:format("Pong finished~n", []), | |
Timer_PID ! finished; | |
{ping, Ping_PID} -> | |
io:format("Received ping. Sending pong~n", []), | |
Ping_PID ! pong, | |
pong(Timer_PID) | |
end. | |
ending_timer() -> | |
Start_time = now(), | |
receive | |
finished -> | |
Diff_time = timer:now_diff(now(), Start_time), | |
io:format("Ending timer finished~n", []), | |
io:format("~p~n", [Diff_time]) | |
end. | |
start(N) -> | |
Timer_PID = spawn(ping_module, ending_timer, []), | |
Pong_PID = spawn(ping_module, pong, [Timer_PID]), | |
spawn(ping_module, ping, [N, Pong_PID]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example shell session:
Eshell V5.8.5 (abort with ^G)
1> c(ping_module).
{ok,ping_module}
2> ping_module:start(1000).
Sending ping
<0.41.0>
Received ping. Sending pong
Received pong
Sending ping
...(redacted)... circa 1000 ping/pongs later...
ping finished
Pong finished
Ending timer finished
107355