Created
January 31, 2019 14:49
-
-
Save jimm/0fb28eb070a82151274bd3c7f6872521 to your computer and use it in GitHub Desktop.
Elixir process receive loop / state / response example
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
#!/usr/bin/env elixir | |
defmodule Sync do | |
def pingpong do | |
# Create process and save pid. | |
child = spawn(Sync, :loop, [0]) # module, sym, args | |
# Send some messages to the child | |
send(child, {self(), :count}) | |
send(child, {self(), :ping}) | |
send(child, {self(), :count}) | |
send(child, {self(), :what?}) | |
send(child, {self(), :done}) | |
# Listen for messages from the child | |
handle_return_messages(child) | |
end | |
def handle_return_messages(child) do | |
# Pattern match against messages coming to self(). | |
# "^child" means "match the value of child" | |
# "child" would mean "shove the first value into child" | |
receive do | |
{^child, :pong} -> | |
IO.puts("pong!") | |
handle_return_messages(child) | |
{^child, :count, count} -> | |
IO.puts("count: #{count}") | |
handle_return_messages(child) | |
{_, :done} -> | |
IO.puts("done") | |
msg -> | |
IO.inspect(msg, label: "some other message from child") | |
handle_return_messages(child) | |
end | |
end | |
# Initial state is passed in. | |
def loop(count) do | |
receive do | |
{from, :ping} -> | |
IO.puts("ping!") | |
send(from, {self(), :pong}) | |
loop(count + 1) | |
{from, :count} -> | |
send(from, {self(), :count, count}) | |
loop(count) | |
{from, :done} -> | |
send(from, {self(), :done}) | |
msg -> | |
IO.inspect(msg, label: "inside process loop") | |
loop(count) | |
end | |
end | |
end | |
Sync.pingpong |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment