# PSA: Reasoning about scope rules and multithreading

**URL:** <https://discourse.julialang.org/t/psa-reasoning-about-scope-rules-and-multithreading/56967>\
**Category:** General Usage\
**Tags:** multithreading, scope\
**Created:** [March 11, 2021, 7:06pm UTC](https://discourse.julialang.org/t/psa-reasoning-about-scope-rules-and-multithreading/56967 "2021-03-11T19:06:55Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![heliosdrm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/heliosdrm/32/3851_2.png) [@heliosdrm](https://discourse.julialang.org/u/heliosdrm)\
**Post date:** [March 11, 2021, 7:06pm UTC](https://discourse.julialang.org/t/psa-reasoning-about-scope-rules-and-multithreading/56967/1 "2021-03-11T19:06:55Z")

</div>

Perhaps this has been discussed before and I missed it, but during my first experimentation with multithreading, I suddenly realized that Julia’s scoping rules in loops, which a number of people find confusing (including myself when I first learnt about them), are really convenient in that context.

One of the things that made me wary of taking advantage of multithreading before, was fear of screwing up the values of the variables when running the iterations in god-knows-which-order (I had not learnt the meaning of “race condition” until recently, but I had an intuition of the concept). And when I finally decided to go for it in Julia, I was conforted to realize that each iteration creates its own scope, so that I only had to take care of the variables that have been defined _outside_ the loop: I can trust that variables that are exclusively defined inside the loop can’t be “touched” by any other iteration that runs in parallel.

@StefanKarpinski [said once that the main motivation for Julia’s scoping rules were closures](https://discourse.julialang.org/t/why-not-an-even-harder-scope/50087/14). But even if this advantage on multithreading is only a nice side effect, I think that it is worth to mention it. Probably nobody will care about either closures or multithreading on their first day with Julia, but the benefit of keeping variables apart between iterations in threaded loops is easy to explain and understand - in my opinion even easier than the advantages that Julia’s scope rules have for creating closures.

---

_[View the full topic](https://discourse.julialang.org/t/psa-reasoning-about-scope-rules-and-multithreading/56967)._
