typestar

Task.async in Elixir

Three reef surveys run in parallel processes and finish in the time of one.

# Task.async starts a process per job; await_many gathers the answers.
survey = fn reef ->
  Process.sleep(100)
  {reef, :healthy}
end

tasks =
  Enum.map(["north", "east", "lagoon"], fn reef ->
    Task.async(fn -> survey.(reef) end)
  end)

IO.inspect(Task.await_many(tasks), label: "surveys")
IO.puts("three dives, one sleep of waiting")

How it works

  1. survey stands in for slow field work with Process.sleep.
  2. Task.async starts one process per reef and returns a handle for each.
  3. Task.await_many collects all three answers in about one sleep, not three.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
328
Tokens
81
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 2 of 3 in Processes, step 23 of 27 in Language basics.

← Previous Next →