bfletch
bfletch

Reputation: 411

Scope of variables inside threaded for loops?

In the following example

shared_arr = zeros(4000)
Threads.@threads for thread = 1:4
    tmp_arr = rand(1000)
    for i = 1:1000
        shared_arr[(thread - 1)*1000+i] = tmp_arr[i]
    end
end

I believe shared_arr is shared among all threads. Is tmp_arr allocated 4 times so that each thread has it's own tmp_arr?

Upvotes: 4

Views: 81

Answers (1)

ntdef
ntdef

Reputation: 504

According to the scoping rules described in the documentation, a new scope is introduced whenever a for-loop is invoked. Since tmp_arr isn't declared prior to the loop, it will be a distinct value in each iteration of the for loop. Note that rand might not be threadsafe however per @Lyndon White's comment.

Upvotes: 1

Related Questions