Created
June 20, 2013 04:08
-
-
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.
This file contains 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
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