Created
June 20, 2013 16:25
-
-
Save benjamintanweihao/5824278 to your computer and use it in GitHub Desktop.
Fibonacci Server in Elixir
This file contains hidden or 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
| import Enum | |
| defmodule FibSolver do | |
| def fib(scheduler) do | |
| # This will send to the scheduler a ready message | |
| # once its done calculating. Notice the call to | |
| # fib(scheduler) which will invoke this line of | |
| # code again. | |
| scheduler <- { :ready, self } | |
| receive do | |
| { :fib, n, client } -> | |
| client <- { :answer, n, fib_calc(n), self } | |
| fib(scheduler) | |
| { :shutdown } -> | |
| exit(0) | |
| end | |
| end | |
| defp fib_calc(0), do: 1 | |
| defp fib_calc(1), do: 1 | |
| defp fib_calc(n), do: fib_calc(n-1) + fib_calc(n-2) | |
| end | |
| defmodule Scheduler do | |
| def run(num_processes, module, func, to_calculate) do | |
| # Spawns processes, and records their pids | |
| processes = map(1..num_processes, fn(_) -> spawn(module, func, [self]) end) | |
| schedule_processes(to_calculate, [], processes) | |
| end | |
| defp schedule_processes(queue, results, processes) do | |
| receive do | |
| { :ready, pid } when length(queue) > 0 -> | |
| [ next | tail ] = queue | |
| pid <- { :fib, next, self } | |
| schedule_processes(tail, results, processes) | |
| # No more things to process. We can ask out calculators | |
| # to exit | |
| { :ready, pid } -> | |
| pid <- { :shutdown } | |
| if length(processes) > 1 do | |
| schedule_processes(queue, results, List.delete(processes, pid)) | |
| else | |
| Enum.sort(results, fn {n1,_}, {n2,_} -> n1 < n2 end) | |
| end | |
| { :answer, number, factorial, _pid } -> | |
| schedule_processes(queue, [ {number, factorial} | results ], processes) | |
| end | |
| end | |
| end | |
| to_process = [27, 33, 35, 11, 36, 29, 18, 37, 21, 31, 19, 10, 14, 30, | |
| 15, 17, 23, 28, 25, 34, 22, 20, 13, 16, 32, 12, 26, 5] | |
| each 1..10, fn num_processes -> | |
| {time, result} = :timer.tc(Scheduler, :run, [num_processes, FibSolver, :fib, to_process]) | |
| if num_processes == 1 do | |
| # Output the result once. | |
| IO.puts inspect result | |
| IO.puts "\n # time (s)" | |
| end | |
| :io.format "~2B ~.2f~n", [num_processes, time/1000000.0] | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment