Created
November 2, 2015 10:40
-
-
Save bansalakhil/e63a4aa389eee5109a6c to your computer and use it in GitHub Desktop.
Elixir ping-pong
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 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