52 lines
1.4 KiB
Erlang
52 lines
1.4 KiB
Erlang
-module(pingpong).
|
|
-export([main/0]).
|
|
|
|
% this runs two processes and has them talk to each other
|
|
% output:
|
|
%
|
|
% 2> pingpong:main().
|
|
% <0.96.0> received {pong, <0.97.0>, 10}
|
|
% <0.97.0> received {ping, <0.96.0>, 9}
|
|
% <0.96.0> received {pong, <0.97.0>, 8}
|
|
% <0.97.0> received {ping, <0.96.0>, 7}
|
|
% <0.96.0> received {pong, <0.97.0>, 6}
|
|
% <0.97.0> received {ping, <0.96.0>, 5}
|
|
% <0.96.0> received {pong, <0.97.0>, 4}
|
|
% <0.97.0> received {ping, <0.96.0>, 3}
|
|
% <0.96.0> received {pong, <0.97.0>, 2}
|
|
% <0.97.0> received {ping, <0.96.0>, 1}
|
|
% <0.96.0> received {pong, <0.97.0>, 0}
|
|
|
|
|
|
main() ->
|
|
PingerPID = spawn(fun pinger/0),
|
|
PongerPID = spawn(fun ponger/0),
|
|
PingerPID ! {pong, PongerPID, 10}.
|
|
|
|
pinger() ->
|
|
receive
|
|
{pong, PID, N} ->
|
|
io:format("~p received {pong, ~p, ~p}~n", [self(), PID, N]),
|
|
% ignore once we get to 0 or lower
|
|
case N > 0 of
|
|
true -> PID ! {ping, self(), N-1};
|
|
false -> ok
|
|
end,
|
|
% once we're done, go back to the top
|
|
pinger()
|
|
end.
|
|
|
|
|
|
ponger() ->
|
|
receive
|
|
{ping, PID, N} ->
|
|
io:format("~p received {ping, ~p, ~p}~n", [self(), PID, N]),
|
|
% ignore once we get to 0 or lower
|
|
case N > 0 of
|
|
true -> PID ! {pong, self(), N-1};
|
|
false -> ok
|
|
end,
|
|
% once we're done, go back to the top
|
|
ponger()
|
|
end.
|