Multithreading and for loops

Why does this works

using Base.Threads

A = zeros(3,3)

Threads.@threads for col = 1:3
    for row = 1:3
        A[row,col]=(col-1)*3+row
    end
end

display(A)

But this does not work

using Base.Threads

A = zeros(3,3)

Threads.@threads for col = 1:3, row = 1:3
        A[row,col]=(col-1)*3+row
end

display(A)
ERROR: LoadError: syntax: invalid assignment location "col = 1:3"
Stacktrace:
 [1] top-level scope at /Users/ssiew/juliascript/threads02.jl:5
in expression starting at /Users/ssiew/juliascript/threads02.jl:5

Even through the two are practically identical as far as I can tell.

And the non-multithreading version below works as well

using Base.Threads

A = zeros(3,3)

for col = 1:3, row = 1:3
        A[row,col]=(col-1)*3+row
end

display(A)

The macro simply does not have support for loops with two variables, you must specify explicitly which loop you would like to thread by splitting the expression into two explicit loops.

2 Likes