Created
March 31, 2021 11:47
-
-
Save minhajuddin/f479812aeb24069fc4e98694943dc1a2 to your computer and use it in GitHub Desktop.
A game of ping pong between two Elixir processes
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
defmodule Player do | |
def start(p1, p2) do | |
# start their game p1 sends a ping to p2 | |
send(p2, {:ping, p1}) | |
end | |
def play do | |
receive do | |
{input_message, _from = opponent_pid} -> | |
respond(opponent_pid, input_message) | |
play() | |
end | |
end | |
defp respond(opponent_pid, input_message) do | |
IO.puts("RECV #{input_message} FROM #{inspect(opponent_pid)}") | |
Process.sleep(1000) # sleep for easier reading of output | |
send(opponent_pid, {response_for(input_message), _my_pid = self()}) | |
end | |
defp response_for(:ping), do: :pong | |
defp response_for(:pong), do: :ping | |
end | |
p1 = spawn(Player, :play, []) | |
p2 = spawn(Player, :play, []) | |
Player.start(p1, p2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment