Created
March 23, 2017 16:53
-
-
Save Arkham/f86fb62463d242c8c5aa2a09147652c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Taskie do | |
def pbump(n) do | |
chunk_size = div(n, 10) | |
1..n | |
|> Enum.chunk(chunk_size, chunk_size, []) | |
|> Enum.map(fn(chunk) -> | |
chunk | |
|> Enum.map(fn(v) -> Task.async(fn() -> Process.sleep(1000); bump(v) end)end) | |
|> Enum.map(fn(t) -> Task.await(t) end) | |
end) | |
end | |
defp bump(v), do: v + 1 | |
defstruct owner: nil, pid: nil, ref: nil | |
def async(fun) do | |
task_ref = make_ref() | |
owner = self() | |
pid = spawn_link(fn -> | |
receive do | |
{^task_ref, ref} -> | |
result = fun.() | |
send owner, {ref, result} | |
end | |
end) | |
ref = Process.monitor(pid) | |
send(pid, {task_ref, ref}) | |
%Taskie{ref: ref, pid: pid, owner: owner} | |
end | |
def await(task, timeout \\ 5_000) do | |
%{ref: ref} = task | |
receive do | |
{^ref, result} -> | |
Process.demonitor(ref, [:flush]) | |
result | |
after | |
timeout -> | |
exit({:timeout, {__MODULE__, | |
:await, | |
[task, timeout]}}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment