Created
July 2, 2018 16:32
-
-
Save Zambito1/039c685208cb3fa35286f418b2116baa to your computer and use it in GitHub Desktop.
Creates two processes that will bounce back and forth to count up to the input value
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 BouncingCounter do | |
def even(max, main_pid) do | |
receive do | |
{:inc, odd_pid, n} when n <= max -> | |
IO.puts("EVEN: Count currently at #{n}") | |
send(odd_pid, {:inc, self(), n + 1}) | |
even(max, main_pid) | |
{:inc, even_pid, n} when n > max -> | |
send(even_pid, {:done}) | |
{:done} -> send(main_pid, {:done}) | |
end | |
end | |
def odd(max, main_pid) do | |
receive do | |
{:inc, even_pid, n} when n <= max -> | |
IO.puts("ODD: Count currently at #{n}") | |
send(even_pid, {:inc, self(), n + 1}) | |
odd(max, main_pid) | |
{:inc, even_pid, n} when n > max -> | |
send(even_pid, {:done}) | |
{:done} -> send(main_pid, {:done}) | |
end | |
end | |
def main do | |
{max, _} = IO.gets("Enter the max value: ") |> Integer.parse | |
odd_pid = spawn(BouncingCounter, :odd, [max, self()]) | |
even_pid = spawn(BouncingCounter, :even, [max, self()]) | |
IO.puts "Starting counter... 1 to #{max}" | |
send(odd_pid, {:inc, even_pid, 1}) | |
receive do | |
{:done} -> IO.puts("Count complete!") | |
end | |
end | |
end | |
BouncingCounter.main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment