Julia Async Tasks
Async tasks are pieces of work that run without waiting for each other. A task can start, and the main work can collect its result later.
One task returns one value
A task adds the numbers from one to ten. Fetching it gives the total.
task = @async sum(1:10)
println(fetch(task))Two tasks are fetched in a fixed order
Both tasks start before either result is fetched. The first result prints before the second result.
first_task = @async 10 * 2
second_task = @async 3 * 4
println(fetch(first_task))
println(fetch(second_task))Sync waits for every task inside it
Two tasks fill two slots inside a sync block. Both slots are full when the block ends.
function synced()
results = [0, 0]
@sync begin
@async results[1] = 6 * 7
@async results[2] = 8 * 9
end
return results
end
println(synced())Example
first_task = @async sum(1:5)
second_task = @async sum(6:10)
third_task = @async sum(11:15)
first_value = fetch(first_task)
second_value = fetch(second_task)
third_value = fetch(third_task)
println(first_value)
println(second_value)
println(third_value)
println(first_value + second_value + third_value)Key points
- Use @async to start a task beside the main work.
- Use fetch to wait for a task and get its result.
- Use @sync to wait for every task inside it to finish.
- Fetch results in a fixed order, so the printed order never changes.
- Use a task result like any other value once it is fetched.
In this example, three tasks add three ranges, the results are fetched in a fixed order, and the three results add to 120.
Note
A task result is only safe to use after fetch has returned it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Two tasks are started with @async. How are their results printed in a fixed order?