# Unexpected behavior possibly due to how scope and multithreading works on 1.4.2

**URL:** https://discourse.julialang.org/t/unexpected-behavior-possibly-due-to-how-scope-and-multithreading-works-on-1-4-2/58412
**Category:** General Usage
**Tags:** multithreading, scope
**Created:** [April 2, 2021, 5:08am UTC](https://discourse.julialang.org/t/unexpected-behavior-possibly-due-to-how-scope-and-multithreading-works-on-1-4-2/58412 "2021-04-02T05:08:08Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![dmitrip](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmitrip/32/13994_2.png) [@dmitrip](https://discourse.julialang.org/u/dmitrip)
#### Post date: [April 2, 2021, 5:08am UTC](https://discourse.julialang.org/t/unexpected-behavior-possibly-due-to-how-scope-and-multithreading-works-on-1-4-2/58412/1 "2021-04-02T05:08:08Z")

</div>

This multithreading behavior with a weird “fix” happens on 1.4.2 for me, but not 1.5 or 1.6. I don’t understand what I’m doing wrong, so I’m wary of just upgrading and forgetting about it:

```julia
module M
function f()
    x = zeros(Int, 10000)
    Threads.@threads for i in 1:length(x)
        n = i
        x[n] = n
    end
    n = sum(x) # weird behavior "fixed" if we change 'n' to 
    return n # some other name here and here
end
println(f()) # should print 50005000, but does not
end

```

But instead of printing 50005000 at the end, we get a random number each time we run. This is seemingly fixed by changing

```julia
n = sum(x)
return n

```

to

```julia
a = sum(x)
return a

```

Am I misunderstanding scoping for `n` inside `@threads` ? Thank you!

---

<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: [April 2, 2021, 5:22am UTC](https://discourse.julialang.org/t/unexpected-behavior-possibly-due-to-how-scope-and-multithreading-works-on-1-4-2/58412/2 "2021-04-02T05:22:35Z")

</div>

This is [Race condition caused by variable scope getting lifted from a multithreaded context · Issue #14948 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/14948)

The `n` after the loop lifts the scope of `n` so you now have a race condition.

---

<div class="post-metadata">

### Author: ![dmitrip](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmitrip/32/13994_2.png) [@dmitrip](https://discourse.julialang.org/u/dmitrip)
#### Post date: [April 2, 2021, 5:30am UTC](https://discourse.julialang.org/t/unexpected-behavior-possibly-due-to-how-scope-and-multithreading-works-on-1-4-2/58412/3 "2021-04-02T05:30:49Z")

</div>

Thanks for pointing to that issue.
