Wednesday, April 15, 2026

@async in Julia is not parallelism - but @Thread.spawn is...

 The Core Idea

In Julia, @async gives you concurrency, not parallelism.

  • @async → runs multiple tasks, but on the same thread
  • Threads.@spawn → runs tasks on multiple CPU threads (true parallelism)

Demonstration 1

function task(name)
println("$name running on thread ", Threads.threadid())
sleep(1)
println("$name finished on thread ", Threads.threadid())
end

@sync begin
@async task("Task A")
@async task("Task B")
end

If we run the above code, we will get 

Task A running on thread 1

Task B running on thread 1

Task A finished on thread 1

Task B finished on thread 1

What is happening internally?

Julia uses cooperative scheduling for @async:

  • Tasks yield control (e.g., sleep, I/O)
  • Scheduler switches between them
  • But execution remains on one OS thread

As you can see from the output, both tasks are running on the same thread.

Demonstration 2

function task(name)
println("$name running on thread ", Threads.threadid())
sleep(1)
println("$name finished on thread ", Threads.threadid())
end

@sync begin
Threads.@spawn task("Task A")
Threads.@spawn task("Task B")
end

If we run the above code, we will get

Task B running on thread 3
Task A running on thread 4
Task B finished on thread 3
Task A finished on thread 4

As you can see from the output, two threads are running in parallel.

Summary


Feature @async Threads.@spawn
Threads used    Single thread    Multiple threads
Parallelism        No        Yes
Concurrency        Yes        Yes
Best forI/O, networking        CPU-heavy tasks
SchedulingCooperativePreemptive (OS threads)

No comments: