# What's the problem with this simple multi-thread code?

**URL:** <https://discourse.julialang.org/t/whats-the-problem-with-this-simple-multi-thread-code/77626>\
**Category:** General Usage\
**Tags:** question\
**Created:** [March 9, 2022, 10:01am UTC](https://discourse.julialang.org/t/whats-the-problem-with-this-simple-multi-thread-code/77626 "2022-03-09T10:01:10Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![tkf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkf/32/17635_2.png) [@tkf](https://discourse.julialang.org/u/tkf)\
**Post date:** [March 9, 2022, 4:48pm UTC](https://discourse.julialang.org/t/whats-the-problem-with-this-simple-multi-thread-code/77626/10 "2022-03-09T16:48:32Z")

</div>

> [@photor](#):
>
> ```julia
> function loop_dot_auto(x, A, y; ntasks = Threads.nthreads())
> s = zeros(ntasks)
> @inbounds Threads.@threads for i = eachindex(y)
> 
> ```

`@inbounds` needs to go inside `@threads` [What is the cause of this performance difference between Julia and Cython? - #4 by tkf](https://discourse.julialang.org/t/what-is-the-cause-of-this-performance-difference-between-julia-and-cython/58886/4)

In general, try minimizing the scope of `@inbounds`.

> [@lmiq](#):
>
> ```julia
> julia> function loop_dot_serial(x, A, y)
> s = 0.
> for i = eachindex(y)
> for k = eachindex(x)
> s += x[k]*A[k,i]*y[i]
> 
> ```

I think this needs `@inbounds` to compare this properly with LoopVectorization.jl and Tullio.jl. This also applies to `@threads` and `@floop`.

> [@lmiq](#):
>
> I am trying to avoid the hot cache by re-initializing the arrays every time.

GC may re-use the same memory region. Maybe a more robust approach is to allocate a lot of arrays such that the total number of bytes is at least as large as (say) a double of the L3 cache size and use them one by one.

---

_[View the full topic](https://discourse.julialang.org/t/whats-the-problem-with-this-simple-multi-thread-code/77626)._
