# Global variables and threads

**URL:** https://discourse.julialang.org/t/global-variables-and-threads/49068
**Category:** General Usage
**Created:** [October 26, 2020, 7:50pm UTC](https://discourse.julialang.org/t/global-variables-and-threads/49068 "2020-10-26T19:50:25Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [October 26, 2020, 7:50pm UTC](https://discourse.julialang.org/t/global-variables-and-threads/49068/1 "2020-10-26T19:50:25Z")

</div>

I have a function inside a module that I need to be thread-safe. The function looks like:

```
function foo()
    for i=1:n
        sigma = (calculate stuff)
    end
    return sigma
end

```

Of course, the above code doesn’t work, because sigma is local to the for loop. So I define it as a global:

```
function foo()
    for i=1:n
        global sigma = (calculate stuff)
    end
    return sigma
end

```

Question: is the resulting global sigma local to the calling thread, or have I introduced a race condition? If the latter, what’s the idiomatic way to define the variable as local to the thread? I don’t particularly want to introduce a lock on the variable, which would introduce some inefficiency in the code.

---

<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 26, 2020, 8:08pm UTC](https://discourse.julialang.org/t/global-variables-and-threads/49068/2 "2020-10-26T20:08:03Z")

</div>

Use an **existing local** variable, see [Local scope](https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope) in the Julia manual.

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [October 26, 2020, 8:12pm UTC](https://discourse.julialang.org/t/global-variables-and-threads/49068/3 "2020-10-26T20:12:40Z")

</div>

Oh, duh. Thanks.
