Will `@info` corrupt `Threads.@threads for`?

Looks like there’s a variable named j in some surrounding scope. As a result, the binding j is captured and shared among all tasks. Renaming the inner j to something obviously unique, like _j_, should fix the problem (you’ll probably want to find a better name, this is just for demonstration purposes). Alternatively, adding local j in the inner scope should also work.

In other words, Julia’s default scoping rules correspond to using the nonlocal keyword in Python.

One way to avoid this pitfall is to factor out nested local scopes into separate functions. It could look something like this:

function inner_loop_body(sub_j_vec, i)
    j = sub_j_vec[i]
    # @info "inside @threads" i j
    println("inside @threads, i = $i, j = $j")
end

function parallel_CG!(B, θ, β, μ, ν)
    for ite = ...
        ...
        for ba = ...
            sub_j_vec = ...
            println("before entering @threads, sub_j_vec = $sub_j_vec")
            Threads.@threads for i = eachindex(sub_j_vec)
                inner_loop_body(i, sub_j_vec)
            end
            error("No.1 can you see this error??")
        end
    end
end

This way, it’s impossible for the inner j to shadow an outer one.

2 Likes