Skip to content

Instantly share code, notes, and snippets.

@binarytemple
Created December 2, 2015 11:58
Show Gist options
  • Save binarytemple/8d3c9db334c3cdf257f2 to your computer and use it in GitHub Desktop.
Save binarytemple/8d3c9db334c3cdf257f2 to your computer and use it in GitHub Desktop.

Adopted from code I found on Benjamin Tan's blog

Simplest case

Define module

defmodule Helloer do
  def hola(msg) do
    IO.puts "Hola! #{msg}"
  end
end

Spawn & invoke

iex(12)> helloer_pid = spawn(Helloer, :hola, ["foo"])
Hola! foo

Send/Recieve

Spawn a process, but have it block while it awaits a message.

Redefine the module. Note that the original post used older, no-longer valid syntax for the send and recieve, e.g : sender <- "Received: #{msg}. Thank you!". Personally, I prefer this newer, more explicit syntax.

defmodule Helloer do
  def hola do
    receive do
      {sender, msg} ->
        send sender, "Received: '#{msg}'. Thank you!"
    end
  end
end

Then spawn and invoke

helloer_pid = spawn(Helloer, :hola, [])
#PID<0.188.0>
send helloer_pid, {self, "Here's a message for you!"}
{#PID<0.59.0>, "Here's a message for you!"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment