Limited parallel map in Elixir
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 Parallel do | |
def run(funs, max) do | |
tasks = for fun <- funs, do: {make_ref, fun} | |
results = do_run(tasks, max, 0, %{}) | |
for {ref, _} <- tasks, do: results[ref] | |
end | |
defp do_run([], _max, 0, results) do | |
results | |
end | |
defp do_run([{ref, fun} | tasks], max, workers, results) when workers < max do | |
caller = self | |
spawn_link fn -> | |
send caller, {ref, fun.()} | |
end | |
do_run(tasks, max, workers + 1, results) | |
end | |
defp do_run(tasks, max, workers, results) do | |
results = receive do | |
{ref, result} -> Map.put(results, ref, result) | |
end | |
do_run(tasks, max, workers - 1, results) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by http://jmilet.github.io/processes/elixir/erlang/2016/04/04/limited-pmap.html