Skip to content

Instantly share code, notes, and snippets.

@bansalakhil
Created November 2, 2015 10:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bansalakhil/e63a4aa389eee5109a6c to your computer and use it in GitHub Desktop.
Save bansalakhil/e63a4aa389eee5109a6c to your computer and use it in GitHub Desktop.
Elixir ping-pong
defmodule PingPong do
import :timer
@timer 500
def ping(x) do
receive do
{pong_pid, n} when n <= x -> IO.puts ("Ping #{n}")
send pong_pid, { self, (n) }
sleep @timer
ping(x)
end
end
def pong(x) do
receive do
{ping_pid, n} when n <= x -> IO.puts ("Pong #{n}")
send ping_pid, {self, (n + 1) }
pong(x)
end
end
def run(n) do
{ping_pid, _} = spawn_monitor(PingPong, :ping, [n])
{pong_pid, _} = spawn_monitor(PingPong, :pong, [n])
send ping_pid, {pong_pid, 1}
receive do
msg -> IO.puts "Message received: #{msg}"
end
end
end
PingPong.run(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment