Unexpected behavior possibly due to how scope and multithreading works on 1.4.2

This multithreading behavior with a weird “fix” happens on 1.4.2 for me, but not 1.5 or 1.6. I don’t understand what I’m doing wrong, so I’m wary of just upgrading and forgetting about it:

module M
function f()
    x = zeros(Int, 10000)
    Threads.@threads for i in 1:length(x)
        n = i
        x[n] = n
    n = sum(x) # weird behavior "fixed" if we change 'n' to 
    return n   # some other name here and here
println(f()) # should print 50005000, but does not

But instead of printing 50005000 at the end, we get a random number each time we run. This is seemingly fixed by changing

n = sum(x)
return n


a = sum(x)
return a

Am I misunderstanding scoping for n inside @threads ? Thank you!

This is Race condition caused by variable scope getting lifted from a multithreaded context · Issue #14948 · JuliaLang/julia · GitHub

The n after the loop lifts the scope of n so you now have a race condition.


Thanks for pointing to that issue.