Julia Threads at a First Look
Threads are separate lines of work that run loop rounds at the same time. Each round still does its own work, and the results are combined after the loop.
Separate slots hold separate results
Each round writes its own slot. The finished list shows every square.
function squares(n)
results = Vector{Int}(undef, n)
Threads.@threads for i in 1:n
results[i] = i * i
end
return results
end
println(squares(4))Partial totals combine into one total
Two chunks are added separately. Their partial totals add to the full total.
function chunk_total()
ranges = [(1, 5), (6, 10)]
partials = [0, 0]
Threads.@threads for c in 1:2
partials[c] = sum(ranges[c][1]:ranges[c][2])
end
return partials
end
println(chunk_total())
println(sum(chunk_total()))A parallel total matches the serial total
Four chunks are added in parallel. The serial sum gives the same number.
function parallel_total()
ranges = [(1, 25), (26, 50), (51, 75), (76, 100)]
partials = [0, 0, 0, 0]
Threads.@threads for c in 1:4
partials[c] = sum(ranges[c][1]:ranges[c][2])
end
return sum(partials)
end
println(parallel_total())
println(sum(1:100))Example
function chunked_total(values)
partials = [0, 0, 0]
Threads.@threads for c in 1:3
partials[c] = sum(values[(c - 1) * 2 + 1:c * 2])
end
return partials
end
amounts = [10, 20, 30, 40, 50, 60]
partials = chunked_total(amounts)
println(partials)
println(sum(partials))Key points
- Use Threads.@threads to share a for loop across threads.
- Use a separate slot for each round, so no two rounds write the same place.
- Use partial results to hold the total of one chunk of work.
- Use integer addition to combine partial results in order.
- Use the serial total to check a parallel total.
In this example, sales are split into three chunks, each chunk total goes into its own slot, and the chunk totals add in order to 210.
Note
A parallel loop still runs correctly with one thread, and its result stays the same.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Why does each chunk write to its own slot in a parallel loop?