October 2014
Intermediate to advanced
280 pages
7h 20m
English
An Elixir task is a function that runs in the background.
| tasks/tasks1.exs | |
| | defmodule Fib do |
| | def of(0), do: 0 |
| | def of(1), do: 1 |
| | def of(n), do: Fib.of(n-1) + Fib.of(n-2) |
| | end |
| | |
| | IO.puts "Start the task" |
| | worker = Task.async(fn -> Fib.of(20) end) |
| | IO.puts "Do something else" |
| | # ... |
| | IO.puts "Wait for the task" |
| | result = Task.await(worker) |
| | |
| | IO.puts "The result is #{result}" |
The call to Task.async creates a separate process that runs the given function. The return value of async is a task descriptor (actually a PID and a ref) that we’ll use to identify the task later.
Once the task is running, the code continues with other work. When it wants to get the function’s value, it calls Task.await, passing in ...
Read now
Unlock full access