Skip to content

Instantly share code, notes, and snippets.

@padde
Last active April 10, 2016 16:48
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 padde/b350dbc81f458898f08417d804e793aa to your computer and use it in GitHub Desktop.
Save padde/b350dbc81f458898f08417d804e793aa to your computer and use it in GitHub Desktop.
Limited parallel map in Elixir
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
@padde
Copy link
Author

padde commented Apr 10, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment