Skip to content

Instantly share code, notes, and snippets.

@benjamintanweihao
Created June 20, 2013 04:08
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 benjamintanweihao/5820249 to your computer and use it in GitHub Desktop.
Save benjamintanweihao/5820249 to your computer and use it in GitHub Desktop.
Fred and Betty exercise from Programming Elixir, Chapter 12 Write a program that spawns two processes, and then passes each a unique token (for example “fred” and “betty”). Have them send the tokens back.
defmodule Echo do
def echo(token, caller_pid) do
IO.puts "Sending #{inspect token} to #{inspect caller_pid}"
caller_pid <- { caller_pid, token }
end
end
defmodule Receiver do
def report(times) do
Enum.map(1..times,
fn(_) ->
receive do
{ caller_pid, token } ->
caller_pid <- IO.puts "Received #{inspect token} back!"
_ -> IO.puts "You shouldn't see this!"
end
end)
end
end
# We need to do the above reassignment because
# the call the spawn changes the value of 'self'
me = self
spawn fn -> Echo.echo(:fred, me) end
spawn fn -> Echo.echo(:betty, me) end
# This won't work though (notice the 'self'):
# spawn fn -> Echo.echo(:fred, self) end
# spawn fn -> Echo.echo(:betty, self) end
# The value of self is the pid of the spawned process.
Receiver.report(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment