Julia Async in Depth
Async in depth means starting tasks that run alongside the main task and collecting their results safely. A failed task reports its error when its result is collected, and a channel hands work to workers one item at a time.
A failed task error is caught as a fixed message
A task fails, fetch throws its error again, and a catch prints one fixed message.
t = @async error("task failed")
try
fetch(t)
catch
println("task failed")
endSync waits for both tasks
Two tasks write two separate slots, and sync waits until both tasks finish.
function sync_total()
vals = [0, 0]
@sync begin
@async vals[1] = 40
@async vals[2] = 2
end
return sum(vals)
end
println(sync_total())Channels hand work to two workers
A channel holds four jobs, two workers take jobs from it, and their partial totals add to the full total.
function work_total()
jobs = Channel{Int}(10)
for v in [10, 20, 30, 40]
put!(jobs, v)
end
close(jobs)
partials = [0, 0]
@sync begin
@async for job in jobs
partials[1] += job
end
@async for job in jobs
partials[2] += job
end
end
return sum(partials)
end
println(work_total())Example
function channel_work()
jobs = Channel{Int}(10)
for v in [10, 20, 30, 40]
put!(jobs, v)
end
close(jobs)
partials = [0, 0]
@sync begin
@async for job in jobs
partials[1] += job
end
@async for job in jobs
partials[2] += job
end
end
return sum(partials)
end
t = @async error("task failed")
try
fetch(t)
catch
println("task failed")
end
println(channel_work())Key points
- Task error: fetch on a failed task throws the same error again in the calling task.
- Use try and catch around fetch to turn a task error into a fixed message.
- Use @sync to wait for every task started inside its block.
- Channel work: a producer puts work into a channel and workers take work from it.
- Channel loop: workers in a for loop over a channel take one item at a time.
In this example, a failed task is caught and prints one fixed message, then a channel hands four jobs to two workers, and the example prints their combined total.
Note
a channel is closed when no more work will arrive, so worker loops can end.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What happens when fetch is called on a failed task?