Strange behavior of @spawn

I do not understand what is going on here:

julia> test(i,j) = println("i = $i , j = $j")
       i = 0 
       for j in 1:4
         global i += 1
         Threads.@spawn test(i,j)
       end

i = 4 , j = 2
julia> i = 4 , j = 1
julia> i = 4 , j = 3
i = 4 , j = 4

Why I get the same i=4 value for all calls?

1 Like

Well, I think that the function takes longer to be called in the specific thread than what the loop takes to run… correct?

Yes. It is exactly that. You can see the difference if you put a sleep(1) after each @spawn.

2 Likes