Skip to content

Instantly share code, notes, and snippets.

@sferik
Forked from josephwilk/future.ex
Last active October 23, 2018 18:46
Show Gist options
  • Save sferik/6116479 to your computer and use it in GitHub Desktop.
Save sferik/6116479 to your computer and use it in GitHub Desktop.
defmodule Future do
def new(fun) do
fn(x) ->
spawn_link fn ->
value = try do
{ :ok, fun.(x) }
rescue
e -> { :error, e }
end
receive do
pid -> pid <- {self, value}
end
end
end
end
def value(pid, timeout // :infinity, default // {:error, :timeout}) do
pid <- self
receive do
{^pid, {:ok, value}} -> value
{^pid, {:error, e}} -> raise e
after
timeout -> default
end
end
end
defmodule Parallel do
def pmap(collection, fun) do
collection
|> Enum.map(Future.new(fun))
|> Enum.map(Future.value(&1))
end
end
IO.inspect Parallel.pmap([1, 2, 3, 4], fn x -> :timer.sleep(1000); x * x end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment