# Race condition with local variable in @threads for loop

**URL:** <https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163>\
**Category:** General Usage\
**Tags:** multithreading\
**Created:** [October 28, 2020, 7:51am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163 "2020-10-28T07:51:29Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![josePereiro](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/josepereiro/32/17322_2.png) [@josePereiro](https://discourse.julialang.org/u/josePereiro)\
**Post date:** [October 28, 2020, 7:51am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163/1 "2020-10-28T07:51:29Z")

</div>

Hi, im trying to figure why this code throw and AssertionError inside the most inner loop. My current understanding is that julia will split the top loop into a number of pieces and spawn each piece to a separate thread. So, I just interpret the whole code inside the top loop as always running in the context of a given task.

Why then is the second assertion triggered?  
Does julia spawn the inner for loop too?  
If so, How can I avoid it?

```julia
# test.jl
import Base.Threads: @threads, nthreads

function test()
    @threads :static for i in 1:100

        d = Dict(:a => Dict())
        a = d[:a]
        @assert a === d[:a]

        # Line 12: This throw an AssertionError
        for j in 1:100; @assert a === d[:a] end 
    end
    a = [] # If this line is commented the problem disappears 
end

println("Running test (-t$(nthreads()))")
for i = 1:500; test() end

```

```julia
$ julia -t4 test.jl
ERROR: LoadError: TaskFailedException:
AssertionError: a === d[:a]
Stacktrace:
 [1] macro expansion at /Users/Pereiro/Documents/dev/threads_issue/test.jl:12 [inlined]
 [2] (::var"#41#threadsfor_fun#1"{UnitRange{Int64}})(::Bool) at ./threadingconstructs.jl:81
 [3] (::var"#41#threadsfor_fun#1"{UnitRange{Int64}})() at ./threadingconstructs.jl:48
[...]

```

Something strange that makes me think I’m missing something is that if I comment the `a=[]` line, the error doesn’t happen.

My version info

```julia
$ julia -e "using InteractiveUtils; versioninfo()"
Julia Version 1.5.2
Commit 539f3ce943 (2020-09-23 23:17 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.7.0)
  CPU: Intel(R) Core(TM) i5-8210Y CPU @ 1.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-9.0.1 (ORCJIT, skylake)
Environment:
  JULIA_NUM_THREADS = 4

```

Any help will be appreciated 🙂

Thanks!

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [October 28, 2020, 8:19am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163/2 "2020-10-28T08:19:44Z")

</div>

[https://github.com/JuliaLang/julia/issues/14948](https://github.com/JuliaLang/julia/issues/14948)

The last assignment makes the variable `a` have a scope outside the threads section.

---

<div class="post-metadata">

**Author:** ![pbayer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pbayer/32/11675_2.png) [@pbayer](https://discourse.julialang.org/u/pbayer)\
**Post date:** [October 28, 2020, 8:21am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163/3 "2020-10-28T08:21:26Z")

</div>

`a` has to be strictly local to `@threads for`. Your code seems to make it an existing local variable (see Kristoffer’s comment). Then threads interfere with each other. Make it explicitly [`local`](https://docs.julialang.org/en/v1/base/base/#local) and it runs.

```julia
function test()
    @threads for i in 1:100
        ...
        local a = d[:a]
        ...
    end
    a = [] # ...
end

```

PS: edited

---

<div class="post-metadata">

**Author:** ![josePereiro](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/josepereiro/32/17322_2.png) [@josePereiro](https://discourse.julialang.org/u/josePereiro)\
**Post date:** [October 29, 2020, 2:12am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163/4 "2020-10-29T02:12:46Z")

</div>

Uff, I wouldn’t figured out by myself, thanks! I will change the title for improve findability, any suggestion?

---

<div class="post-metadata">

**Author:** ![pbayer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pbayer/32/11675_2.png) [@pbayer](https://discourse.julialang.org/u/pbayer)\
**Post date:** [October 29, 2020, 7:00am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163/5 "2020-10-29T07:00:56Z")

</div>

ok, I have clarified my response.

Perhaps you could call it “Race condition with local variable in @threads for”

---

<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:** [October 29, 2020, 7:32am UTC](https://discourse.julialang.org/t/race-condition-with-local-variable-in-threads-for-loop/49163/6 "2020-10-29T07:32:44Z")

</div>

FYI `@floop ex for` from [FLoops.jl](https://github.com/JuliaFolds/FLoops.jl) can be used instead of `@threads for` and it’d detect this error. It also shows which variable is causing it:

 ![image](https://global.discourse-cdn.com/julialang/original/3X/2/b/2bcf5c454d82896b50cd14d75012b6acf81f5b8c.png)

`@floop ex for` workarounds common pitfalls of `@threads for` like this one, provides a rich reduction API, and supports multiple backends including GPU, with [FoldsCUDA.jl](https://github.com/JuliaFolds/FoldsCUDA.jl).
