Skip to content

Instantly share code, notes, and snippets.

@Zambito1
Created July 2, 2018 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zambito1/039c685208cb3fa35286f418b2116baa to your computer and use it in GitHub Desktop.
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
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