# How to lock variables in @threads

**URL:** <https://discourse.julialang.org/t/how-to-lock-variables-in-threads/57697>\
**Category:** General Usage\
**Tags:** question, multithreading\
**Created:** [March 22, 2021, 10:02am UTC](https://discourse.julialang.org/t/how-to-lock-variables-in-threads/57697 "2021-03-22T10:02:23Z")\
**Posts on this page:** 1\
**Showing post:** 7

<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:** [March 24, 2021, 1:02am UTC](https://discourse.julialang.org/t/how-to-lock-variables-in-threads/57697/7 "2021-03-24T01:02:30Z")

</div>

I’d rather not recommend `@spawn` to programmers new to threading. It’s a great foundation but difficult to use and loses clarity in the program. For example, while concise and self-contained, @foobar_lv2’s example contains subtly different but yet equivalent definitions of the “monoid” `if res < be be, bp1, bp2 = res, pi, pj end`. There is no syntactic constraint that the required invariance between these two definitions is preserved after subsequent refactorings. Furthermore, when using `@spawn`, you need to understand **`let`** in `let be = Inf64, bp1=-1, bp2=-1.0` is _crucial_ (see [PSA: Reasoning about scope rules and multithreading - #2 by tkf](https://discourse.julialang.org/t/psa-reasoning-about-scope-rules-and-multithreading/56967/2) for why `let` is needed; FYI, FLoops.jl tries to detect this bug).

If you want simple data parallelism like this, I strongly recommend learning how to use mapreduce (or, equivalently, something like FLoops.jl), at least as a first step.

---

_[View the full topic](https://discourse.julialang.org/t/how-to-lock-variables-in-threads/57697)._
