Last active
April 16, 2019 15:25
-
-
Save redink/8c5d57cb4cbb10d4b9c8dd36c5ecd430 to your computer and use it in GitHub Desktop.
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 Pmap do | |
@moduledoc """ | |
Documentation for Pmap. | |
""" | |
def pmap(list, func) do | |
pmap(self(), 0, list, func, []) | |
end | |
@doc false | |
defp pmap(_, _, [], _, pid_list) do | |
pid_list | |
|> receive_result([]) | |
|> IO.inspect() | |
|> Enum.sort() | |
|> Enum.map(fn {_, v} -> v end) | |
end | |
defp pmap(task_owner, index, [head | tail], func, pid_list) do | |
pid = spawn(fn -> | |
Process.sleep(Enum.random(1..1000)) | |
send(task_owner, {self(), index, func.(head)}) | |
end) | |
pmap(task_owner, index + 1, tail, func, [pid | pid_list]) | |
end | |
@doc false | |
defp receive_result([], res_list), do: res_list | |
defp receive_result(pid_list, res_list) do | |
receive do | |
{pid, index, value} -> | |
if Enum.member?(pid_list, pid) do | |
receive_result(List.delete(pid_list, pid), [{index, value} | res_list]) | |
else | |
receive_result(pid_list, res_list) | |
end | |
end | |
end | |
# __end_of_module__ | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment