Julia Threads in Depth
Julia threads in depth means giving each thread its own partial total and then adding those partials in order. Each thread works on its own share, and no thread touches another thread's partial total.
Each thread keeps its own partial total
One loop adds the numbers from 1 to 10, with each thread keeping its own partial total.
function partial_sum()
parts = zeros(Int, Threads.nthreads())
Threads.@threads for i in 1:10
parts[Threads.threadid()] += i
end
return sum(parts)
end
println(partial_sum())Partial totals add up in order
The same idea adds the numbers from 1 to 100, and the ordered sum is the full total.
function partial_sum_hundred()
parts = zeros(Int, Threads.nthreads())
Threads.@threads for i in 1:100
parts[Threads.threadid()] += i
end
return sum(parts)
end
println(partial_sum_hundred())Partial totals can count only even numbers
A thread adds a number to its partial total only when that number is even.
function even_sum()
parts = zeros(Int, Threads.nthreads())
Threads.@threads for i in 1:20
if iseven(i)
parts[Threads.threadid()] += i
end
end
return sum(parts)
end
println(even_sum())Example
function square_sum()
parts = zeros(Int, Threads.nthreads())
Threads.@threads for i in 1:10
parts[Threads.threadid()] += i * i
end
return sum(parts)
end
println(square_sum())Key points
- Partial total: each thread adds only to its own slot in a shared list of partial totals.
- Ordered sum: adding the partial totals from first to last gives the same total on every run.
- Use Threads.@threads to run one loop across several threads.
- Separate slots: a partial total stays exact because only its owner thread writes to it.
- Thread share: each thread handles its own share of the loop range.
In this example, each thread adds the square of its numbers to its own partial total, then the example adds the partial totals in order and prints the full total.
Note
thread counts differ by machine, so this lesson prints totals only and never prints a thread count.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does a per-thread partial total prevent?