Threads.@threads and BitArrays

Issue https://github.com/JuliaLang/julia/issues/33750 is about BitArrays not being threadsafe. My reading: changing elements of a BitArray inside a Threads.@threads for loop can give unpredictable results.

My question is similar, but not exactly the same. In my case, the function creates a new BitArray v inside a Threads.@threads for loop as in

function f2(N)
  v = falses(N+1)
  x = zeros(Int,N,N)
  Threads.@threads for i = 1:N
    v    = falses(N)
    v[i] = true
    x[v,i] .= i
  end
  return x
end

Calling f2(3) sometimes gives diagm(1:3), sometimes not. However, commenting out the v = falses(N+1) statement seems to solve the problem. Alternatively, adding local v also seems to solve the problem. Are these reliable approaches?

This does not have anything to do with BitArrays. Your undefined behavior comes from the fact tthat you are sharing the variable across iterations so you sometimes get v created by one thread used in other threads.

1 Like

you are sharing the variable across iterations

But, v is redefined inside the Threads.@threads for loop. Is it shared because there existed a previous v (defined outside the loop) and/or because it is not declared as a local?

v is not redefined. The variable is reassigned but it is still the same variable.

I argued for making assignment local by default since the current behavior is almost never what you want in Race condition caused by variable scope getting lifted from a multithreaded context · Issue #14948 · JuliaLang/julia · GitHub but Jeff disagrees.

3 Likes