Created
February 18, 2020 15:31
-
-
Save benoittgt/489096ff081c9ac8232284f44440167b to your computer and use it in GitHub Desktop.
Ping Pong in elixir
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 PingPong do | |
| def random do | |
| time = :rand.uniform(1000) | |
| :timer.sleep(time) | |
| time | |
| end | |
| def ping do | |
| receive do | |
| {pong_pid} -> | |
| IO.puts ("Ping") | |
| random() | |
| send pong_pid, { self() } | |
| ping() | |
| end | |
| end | |
| def pong do | |
| receive do | |
| {ping_pid} -> | |
| IO.puts ("Pong") | |
| random() | |
| send ping_pid, { self() } | |
| pong() | |
| end | |
| end | |
| def run do | |
| ping_pid = spawn(PingPong, :ping, []) | |
| pong_pid = spawn(PingPong, :pong, []) | |
| send ping_pid, {pong_pid} | |
| receive do | |
| # but why? | |
| end | |
| end | |
| end | |
| PingPong.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment