Created
October 27, 2017 16:58
-
-
Save alessandro-fazzi/74645f95e375b65b1b6303cc73efd2e7 to your computer and use it in GitHub Desktop.
Elixir excercise ping pong server
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
defmodule Match do | |
def start(max_iterations) when is_integer(max_iterations) and max_iterations > 0 do | |
spawn(__MODULE__, :init, [max_iterations]) | |
end | |
def init(max_iterations) do | |
match = self() | |
player2 = spawn(Player, :start, [:pong, match]) | |
player1 = spawn(Player, :start, [:ping, match]) | |
send(player1, {:pong, player2}) | |
loop([player1, player2], max_iterations) | |
end | |
defp loop(processes, 0) do | |
Enum.each processes, fn process -> | |
Process.exit process, :kill | |
end | |
end | |
defp loop(processes, iterations) do | |
receive do | |
:add -> | |
IO.puts "New iteration received" | |
loop(processes, (iterations - 1)) | |
end | |
end | |
end | |
defmodule Player do | |
def start(name, match) do | |
loop(name, match) | |
end | |
defp loop(name, match) do | |
receive do | |
{message, foe} -> | |
IO.puts "I am #{inspect name} and I've received #{inspect message}" | |
Process.sleep 1_000 | |
send(foe, {name, self()}) | |
send(match, :ad) | |
loop(name, match) | |
_ -> | |
loop(name, match) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment