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
surveystands in for slow field work withProcess.sleep.Task.asyncstarts one process per reef and returns a handle for each.Task.await_manycollects all three answers in about one sleep, not three.
Keywords and builtins used here
EnumIOProcessTaskendfn
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.
Step 2 of 3 in Processes, step 23 of 27 in Language basics.