# Locking properties of AbstractArrays

**URL:** https://discourse.julialang.org/t/locking-properties-of-abstractarrays/4141
**Category:** General Usage
**Tags:** question
**Created:** [June 7, 2017, 3:27pm UTC](https://discourse.julialang.org/t/locking-properties-of-abstractarrays/4141 "2017-06-07T15:27:37Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![shivin9](https://avatars.discourse-cdn.com/v4/letter/s/eb8c5e/32.png) [@shivin9](https://discourse.julialang.org/u/shivin9)
#### Post date: [June 7, 2017, 3:27pm UTC](https://discourse.julialang.org/t/locking-properties-of-abstractarrays/4141/1 "2017-06-07T15:27:37Z")

</div>

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.

```julia
    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

```

```julia
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?

---

<div class="post-metadata">

### Author: ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)
#### Post date: [June 7, 2017, 3:44pm UTC](https://discourse.julialang.org/t/locking-properties-of-abstractarrays/4141/2 "2017-06-07T15:44:30Z")

</div>

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`](https://discourse.julialang.org/t/odd-behavior-from-threads-with-bitwise-and/3191/5)

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.
