Skip to content

Instantly share code, notes, and snippets.

@yowchun93
Last active January 16, 2019 13:20
Show Gist options
  • Save yowchun93/147d0024b1a101cbb93242fbc928f169 to your computer and use it in GitHub Desktop.
Save yowchun93/147d0024b1a101cbb93242fbc928f169 to your computer and use it in GitHub Desktop.
Elixir Message Passing
## Kernel.send/2 function
send(pid, { :an, :arbitary, :term } )
receive do
pattern_1 -> do_something
pattern_2 -> do_something_else
## Example to be executed in IEX
send(self, "a message")
"a message"
receive do
message -> IO.inspect message
end
## if a receive block runs, and the mailbox is empty, the receive block runs indefinately.
receive do
message -> IO.inspect message
after 5000 -> IO.puts "message not received"
end
run_query = fn(query_def) ->
:timer.sleep(2000)
"#{query_def} result"
end
## async_query with message passing
## sending processes
async_query = fn(query_def) ->
caller = self
spawn(fn ->
send( caller, {:query_result, run_query.(query_def)})
end)
end
Enum.each(1..5, &async_query.("query #{&1}"))
# result is stored in the mailbox of the caller process
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment