Skip to content

Instantly share code, notes, and snippets.

@padde

padde/lpmap.exs

Last active Apr 10, 2016
Embed
What would you like to do?
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

This comment has been minimized.

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