Will my variable be modified in a `do` block? Very subtle to anticipate

That one behaves differently inside a function:

function fun()
    s = 0
    Threads.@threads for i = 1:3
        s = i
    end
    return s
end
julia> fun()
3

The content of the @threads loop is put inside an anonymous function by the @threads macro. It will look for an s in an outer local scope. The s in the function is local, so it will be used.

On the other hand, when the @threads loop is defined at top-level, the outer scope with the s is global, so it will not be looked up.

The for loop without @threads is not in a function, it creates a soft scope, and works differently at the REPL.
There’s a lengthy explanation in Scope of Variables · The Julia Language.

There are good reasons for the put code in functions advice.

2 Likes