Created
February 26, 2011 22:23
-
-
Save aerosol/845683 to your computer and use it in GitHub Desktop.
exc#1 concurrency
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(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