Skip to content

Instantly share code, notes, and snippets.

@aerosol
Created February 26, 2011 22:23
Show Gist options
  • Select an option

  • Save aerosol/845683 to your computer and use it in GitHub Desktop.

Select an option

Save aerosol/845683 to your computer and use it in GitHub Desktop.
exc#1 concurrency
-module(processes).
-compile(export_all).
% Interaction between processes, Concurrency
%
% 1. Write a function which starts 2 processes, and sends a message M
% times forewards and backwards between them. After the messages have been
% sent the processes should terminate gracefully.
init(PingPongCount) ->
spawn(?MODULE, pingpong, [PingPongCount]).
start(PingPongCount) ->
[Pinger, Ponger] = [init(PingPongCount), init(PingPongCount)],
Pinger ! {Pinger, serve_shoot, Ponger}.
pingpong(Count) ->
receive
{From, serve_shoot, Ponger} ->
io:format("~p serving PING to ~p", [From, Ponger]),
Ponger ! {From, ping},
pingpong(Count);
{From, ping} when Count >= 1 ->
io:format("PING! ~p replying with pong! (~p)~n", [self(),
Count]),
From ! {self(), pong},
pingpong(Count - 1);
{From, pong} when Count > 1 ->
io:format("PONG! ~p will send ping! (~p) ~n", [self(), Count]),
From ! {self(), ping},
pingpong(Count - 1);
_ ->
io:format("~p Game over. ~p ~n", [self(), Count]),
ok
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment