# Data racing with @threads with "for-loop"

**URL:** <https://discourse.julialang.org/t/data-racing-with-threads-with-for-loop/95863>\
**Category:** New to Julia\
**Tags:** question, bug, multithreading, threads\
**Created:** [March 10, 2023, 12:19pm UTC](https://discourse.julialang.org/t/data-racing-with-threads-with-for-loop/95863 "2023-03-10T12:19:29Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Zerosum](https://avatars.discourse-cdn.com/v4/letter/z/b2d939/32.png) [@Zerosum](https://discourse.julialang.org/u/Zerosum)\
**Post date:** [March 10, 2023, 12:19pm UTC](https://discourse.julialang.org/t/data-racing-with-threads-with-for-loop/95863/1 "2023-03-10T12:19:30Z")

</div>

I figured out that my code is having a data-race problem with @threads. However, I cannot see what is causing the problem and how I can fix this.

```julia

### Generate deterministic sequence

trial = seq_generator(sobol_n);

### Prepare a null vector to collect every vector produced in each thread

    vec_model = Any[]

    for i in 1:Threads.nthreads()
        push!(vec_model,Any[])
    end

### In each thread, simulate and produce objects

    @threads for col in collect(eachcol(trial))

        try 
            moments = simulated_moment(col)     
            d = moments .- collect(values(dictEmpiricalMoments)  
            norm = transpose(d) * W * d         
            input = [col,moments,norm]
            push!(vec_model[threadid()],input)   
   
        catch # in case of error, assign huge value  
            moments = ones(length(dictEmpiricalMoments)) * 10^6      
            d = moments .- collect(values(dictEmpiricalMoments)) # Warning, the order should be in line 
            norm = transpose(d) * W * d         
            input = [col,moments,norm]
            push!(vec_model[threadid()],input)   
       end

    end 

### Merge the vectors 

    sim = vcat(vec_model...)

### Find the row with the minimum norm 

    distance, ind = findmin(last,sim)

```

I get that “ind” can change by each trial, but I’m also having different “distance”.

Once I remove @threads, I get consistent result.

---

<div class="post-metadata">

**Author:** ![j-fu](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/j-fu/32/11373_2.png) [@j-fu](https://discourse.julialang.org/u/j-fu)\
**Post date:** [March 10, 2023, 12:23pm UTC](https://discourse.julialang.org/t/data-racing-with-threads-with-for-loop/95863/2 "2023-03-10T12:23:40Z")

</div>

Just see this recent thread: [Behavior of threads - #29 by lmiq](https://discourse.julialang.org/t/behavior-of-threads/95769/29)

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [March 10, 2023, 12:30pm UTC](https://discourse.julialang.org/t/data-racing-with-threads-with-for-loop/95863/3 "2023-03-10T12:30:30Z")

</div>

But first optimize the serial version. With all those `Any`, doing the calculations and global scope, and a lot of intermediate allocations (like using `collect` unnecessarily, etc), you probably can get huge speedups without going multi-threaded at all.

---

<div class="post-metadata">

**Author:** ![simsurace](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simsurace/32/30216_2.png) [@simsurace](https://discourse.julialang.org/u/simsurace)\
**Post date:** [March 10, 2023, 5:19pm UTC](https://discourse.julialang.org/t/data-racing-with-threads-with-for-loop/95863/6 "2023-03-10T17:19:54Z")

</div>

You could also just do

```julia
using Folds
sim = Folds.map(eachcol(trial)) do col
    # your code from the loop body, without the pushes
    return [col, moments, norm]
end

```
