Locking properties of AbstractArrays

Are AbstractArrays thread safe? I am trying to parallelize a code by using threads and am currently getting some performance gain by using Thread.@threads which shouldn’t come ideally if they were thread-safe.

    Threads.@threads for i in 1 : length(x)
        wndw_low = Int(max(1, low(i)))
        wndw_high = Int(min(stencil_length, high(i)))
        convolve!(x_temp, x, coeffs, i, mid, wndw_low, wndw_high)
    end
function convolve!{T<:Real}(x_temp::AbstractVector{T}, x::AbstractVector{T}, coeffs::SVector,
                   i::Int, mid::Int, wndw_low::Int, wndw_high::Int)
    #=
        Here we are taking the weighted sum of a window of the input vector to calculate the derivative
        at the middle point. This requires choosing the end points carefully which are being passed from above.
    =#
    @inbounds for idx in wndw_low:wndw_high
        x_temp[i] += coeffs[idx] * x[i - (mid-idx)]
    end
end

So my question is that whether the performance will improve if I let threads work on a separate array of their own or is this the optimal way to get performance?

There are many different AbstractArray and they have different thread safety behavior.

In general though. x_temp[i] += is NEVER thread safe if two thread access the same i. It can be thread safe if you can guarantee i are all different for different threads but not if different indices belongs to the same memory location which is the case for BitArray

Performance wise, you should make sure each thread work on different memory. What you are doing should be fine.

Note that I dont think LLVM has enough information to hoist the memory access to x_temp in convolve! it’ll be better if you do xtempi = x_temp[i] before the loop, xtempi += in the loop and x_temp[i] = xtempi after the loop. This is not thread specific.