Jks Liu
Jks Liu

Reputation: 497

Is variable in Julia thread for loop thread local?

Threads.@threads for i in [sth]
    x = 123
    ...
end

Is x thread local. I can not find any document about it.
If not, how can I get a thread local one.

Upvotes: 6

Views: 792

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

Assuming that x is local inside the loop then yes. Here is an example how you can check it:

# julia -t 2 --banner=no
julia> Threads.@threads for i in 1:8
           x = i
           @info Threads.threadid(), i, x
           sleep(rand())
           @info Threads.threadid(), i, x
       end
[ Info: (1, 1, 1)
[ Info: (2, 5, 5)
[ Info: (1, 1, 1)
[ Info: (1, 2, 2)
[ Info: (2, 5, 5)
[ Info: (2, 6, 6)
[ Info: (1, 2, 2)
[ Info: (1, 3, 3)
[ Info: (2, 6, 6)
[ Info: (1, 3, 3)
[ Info: (1, 4, 4)
[ Info: (2, 7, 7)
[ Info: (1, 4, 4)
[ Info: (2, 7, 7)
[ Info: (2, 8, 8)
[ Info: (2, 8, 8)

For each thread whatever is passed inside the for loop body that is annotated with Threads.@threads is wrapped in an anonymous function. You can check it by using @macroexpand function.

Note that it is even more x: gets a new binding with each iteration of the loop (this is a standard behavior of Julia -- no matter if it is single or multi threaded code, see here).

If x is not a local variable inside the for loop this is not true any more as you can see here:

# julia -t 2 --banner=no
julia> function f()
       x = 1
       Threads.@threads for i in 1:8
           x = i
           @info Threads.threadid(), i, x
           sleep(rand())
           @info Threads.threadid(), i, x
       end
       end
f (generic function with 1 method)

julia> f()
[ Info: (1, 1, 5)
[ Info: (2, 5, 5)
[ Info: (1, 1, 5)
[ Info: (1, 2, 2)
[ Info: (2, 5, 2)
[ Info: (2, 6, 6)
[ Info: (2, 6, 6)
[ Info: (2, 7, 7)
[ Info: (1, 2, 7)
[ Info: (1, 3, 3)
[ Info: (1, 3, 3)
[ Info: (1, 4, 4)
[ Info: (2, 7, 4)
[ Info: (2, 8, 8)
[ Info: (2, 8, 8)
[ Info: (1, 4, 8)

Upvotes: 5

Related Questions