# Thread-local let bindings?

**URL:** <https://discourse.julialang.org/t/thread-local-let-bindings/24290>\
**Category:** Performance\
**Created:** [May 16, 2019, 6:10pm UTC](https://discourse.julialang.org/t/thread-local-let-bindings/24290 "2019-05-16T18:10:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![robsmith11](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/robsmith11/32/29641_2.png) [@robsmith11](https://discourse.julialang.org/u/robsmith11)\
**Post date:** [May 16, 2019, 6:10pm UTC](https://discourse.julialang.org/t/thread-local-let-bindings/24290/1 "2019-05-16T18:10:13Z")

</div>

I’m running into performance problems when my multithreaded code allocates heavily, so I’m trying to use let bindings to avoid reallocating large arrays, but I don’t see any way to make the bindings thread-local.

For example, I don’t think the following is thread-safe:

```julia
const rngs = ntuple(Random.MersenneTwister, Threads.nthreads())

let a = zeros(10^6)
    global function f()
        rand!(rngs[Threads.threadid()], a)
        sum(a)
    end
end

Threads.@threads for _ in 1:100 
    f()
end  

```

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [May 16, 2019, 8:07pm UTC](https://discourse.julialang.org/t/thread-local-let-bindings/24290/2 "2019-05-16T20:07:06Z")

</div>

Perhaps you could define a struct to hold your buffer (and perhaps also your RNG) and then define your function to act on that struct?

```julia
struct Foo
  a::Vector{Float64}
  rng::(whatever the correct type is)
end

function f!(f::Foo)
 (do stuff with f.a and f.rng)
end

buffers = [Foo(...) for _ in 1:Threads.nthreads()]
Threads.@threads for _ in 1:100  
  f!(buffers[Threads.threadid()]
end

```
