# Pre-allocated, thread-save buffer arrays

**URL:** <https://discourse.julialang.org/t/pre-allocated-thread-save-buffer-arrays/56715>\
**Category:** General Usage\
**Created:** [March 8, 2021, 6:52am UTC](https://discourse.julialang.org/t/pre-allocated-thread-save-buffer-arrays/56715 "2021-03-08T06:52:48Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jae-Mo\_Lihm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jae-mo_lihm/32/20145_2.png) [@Jae-Mo\_Lihm](https://discourse.julialang.org/u/Jae-Mo_Lihm)\
**Post date:** [March 8, 2021, 6:52am UTC](https://discourse.julialang.org/t/pre-allocated-thread-save-buffer-arrays/56715/1 "2021-03-08T06:52:48Z")

</div>

In my program, I have a loop where I need a buffer array. The required size of the buffer changes only a few times during the run. Also, I am using multithreading. So, the buffer should be thread-safe.

The following script is what I came up with. A const array `_buffer` is declared. Function `_get_buffer` returns the buffer, resizing the array if needed. Is there any problem with this method?

Also, is there a better way, or a package for pre-allocating and changing buffer sizes?

```julia
using Base.Threads

# Preallocated buffer array
const _buffer = [Array{Float64, 2}(undef, 0, 0)]
Threads.resize_nthreads!(_buffer)

"""Get preallocated buffer in a thread-safe way.
Resize buffer if the size is different from the needed size"""
function _get_buffer(buffer::Vector{Array{T, N}}, size_needed::NTuple{N, Int}) where {T, N}
    tid = threadid()
    if size(buffer[tid]) != size_needed
        buffer[tid] = zeros(T, size_needed)
    end
    buffer[tid]
end

# Usage
Nlist = vcat(repeat([40], 10), repeat([60], 10)) # Size of the buffer array for each iteration

@threads for N in Nlist
    arr = _get_buffer(_buffer, (N, N))
    # Do something with arr..
    arr .= 1.0
    println(sum(arr))
end

```
