Skip to content

Instantly share code, notes, and snippets.

@Dania02525
Last active January 4, 2017 19:39
Show Gist options
  • Save Dania02525/4ee8e294a5e9db37406f to your computer and use it in GitHub Desktop.
Save Dania02525/4ee8e294a5e9db37406f to your computer and use it in GitHub Desktop.
Task race, return the winner, ignore the slower tasks (if any)
defmodule Async do
def run do
task1 = Task.async(fn -> :timer.sleep(10000); :slow end)
task2 = Task.async(fn -> :timer.sleep(2000); :fail end)
task3 = Task.async(fn -> :timer.sleep(1000); :fail end)
await([task1, task2, task3])
end
def await(tasks) do
receive do
message ->
case Task.find(tasks, message) do
{:fail, task} ->
await(List.delete(tasks, task))
{reply, _task} ->
reply
nil ->
await(tasks)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment