Created
October 13, 2015 13:37
-
-
Save gpad/c15909b64cce1d98b674 to your computer and use it in GitHub Desktop.
Parallel Fibonacci
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 Fibonacci do | |
def fib(0), do: 0 | |
def fib(1), do: 1 | |
def fib(n), do: fib(n-1) + fib(n-2) | |
end | |
defmodule Fibonacci.Parallel do | |
def fib(n, processes) do | |
(1..processes) |> Enum.map(fn id -> | |
srv = self() | |
pid = spawn(fn -> send(srv, {:fib, {n, Fibonacci.fib(n), self(), id}}) end) | |
{id, pid} | |
end) | |
|> loop_until | |
end | |
defp loop_until([]), do: nil | |
defp loop_until(workers) do | |
receive do | |
{:fib, {nfib, res, from, id}} -> | |
IO.puts "Calculated fibonacci(#{nfib}) -> #{res}, (#{inspect from} - #{id})" | |
workers = Enum.filter workers, fn {i,p} -> !(i == id && p == from) end | |
_ -> | |
IO.puts "Unknown" | |
end | |
loop_until(workers) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment