ZetCode

Julia Tasks Tutorial

last modified November 18, 2026

A task is a lightweight unit of work that can be paused and resumed. Tasks are also called coroutines: unlike operating-system threads, they switch only when the code explicitly gives up control. This tutorial shows how to create tasks, hand control between them, wait for their results, and detect failures.

Julia uses cooperative scheduling: a running task keeps the processor until it finishes or calls yield. Each example below is arranged so that its printed lines have one fixed order, making the output deterministic. Every listing is a standalone main.jl file, verified with Julia 1.13.4.

Creating a Task

The Task constructor wraps a zero-argument function in a task object. Constructing it does not run the function.

main.jl
task = Task(() -> 2 + 3)
schedule(task)
println(fetch(task))

The lambda () -> 2 + 3 is the work to perform. schedule places the task in the run queue, and fetch waits for it to finish and returns its result. Skipping schedule is a real trap: fetching a task that is never queued waits forever, because nothing can ever run it.

$ julia main.jl
5

The @async Macro

The @async macro combines creation and scheduling in one step. It is the usual way to start a task.

main.jl
task = @async 6 * 7
println(fetch(task))

The expression after @async becomes the task's body, and the macro returns the task object. Fetching it yields 42. Macros are explained in the macros tutorial.

$ julia main.jl
42

wait and fetch

Both wait and fetch suspend the caller until a task ends, but only one of them returns the task's value.

main.jl
task = @async 40 + 2
println(istaskdone(task))
println(wait(task))
println(istaskdone(task))
println(fetch(task))

A newly scheduled task is not done yet, so istaskdone starts false. wait returns nothing — it is used for synchronisation only. After waiting, the task is done and fetch can return its result immediately.

$ julia main.jl
false
nothing
true
42

Yielding and Cooperative Scheduling

A task runs without interruption until it calls yield or returns. Calling yield lets the scheduler run another ready task.

main.jl
events = String[]

task = @async begin
    push!(events, "task start")
    yield()
    push!(events, "task end")
end

push!(events, "main start")
yield()
push!(events, "main end")
wait(task)

for e in events
    println(e)
end

Both the main task and the background task append to the same vector, but only at well-defined points: the main task yields once and then waits. With cooperative scheduling the two streams of work interleave only at those explicit yield points. All printing happens afterwards in one loop, so the output order is fixed.

$ julia main.jl
main start
task start
main end
task end

Tasks Start Later

Scheduling a task does not execute it immediately. The body runs the next time the scheduler gets a chance.

main.jl
started = Ref(false)
t = @async begin
    started[] = true
end
println(started[])
wait(t)
println(started[])

A Ref is a one-element container that lets the task write to a value shared with the main program. Right after @async the flag is still false; only after wait(t) has run the task does it become true. This is the essence of cooperative scheduling.

$ julia main.jl
false
true

Producing and Consuming Values

A task can act as a producer by placing values into a shared collection, while the main program consumes them after waiting.

main.jl
values = Int[]
producer = @async begin
    for i in 1:5
        push!(values, i)
        yield()
    end
end

wait(producer)
println(sum(values))
println(length(values))

The producer appends the numbers 1 through 5, yielding after each one. wait is the synchronisation point: only after it returns is the shared vector complete. The main program then consumes the values by summing them and counting them. Julia's Channels provide a more structured alternative for this pattern.

$ julia main.jl
15
5

Waiting for Several Tasks

The foreach function can wait on a whole collection of tasks in a single line.

main.jl
tasks = [@async begin
    yield()
    i * i
end for i in 1:4]

foreach(wait, tasks)
println(sum(fetch(t) for t in tasks))

Four tasks each produce the square of a number from 1 to 4. Waiting on all of them makes it safe to fetch their results; the squares add up to 30. The order in which the tasks run does not matter, because the final sum is the same.

$ julia main.jl
30

The @sync Block

A @sync block waits for all the @async tasks started inside it before continuing.

main.jl
@sync begin
    @async begin
        yield()
        println("inner task finished")
    end
end
println("sync block finished")

The inner task prints its line before the statement after the block, because @sync does not let control leave until every nested task has completed. This is convenient when several tasks must finish before the next stage of a program begins.

$ julia main.jl
inner task finished
sync block finished

Task Failures

If a task's body throws an error, fetch rethrows it wrapped in a TaskFailedException, and istaskfailed reports the failure.

main.jl
t = @async error("something went wrong")
try
    fetch(t)
catch e
    println("failed with TaskFailedException: ", e isa TaskFailedException)
end
println(istaskfailed(t))

The try/catch statement catches the exception. Instead of printing the exception object, which contains an unstable memory address, the example prints a boolean check of its type. Exception handling is covered in the exceptions tutorial.

$ julia main.jl
failed with TaskFailedException: true
true

Best Practices for Tasks

A few guidelines keep task-based code predictable.

Source

Julia Parallel Computing documentation

Julia Tasks and Parallelism documentation

In this article we have created tasks with Task and @async, yielded cooperatively, used wait and fetch, inspected task state with istaskdone and istaskfailed, and grouped tasks with @sync. Channels for passing values between tasks are covered in Julia channels, and exception handling in Julia exceptions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.