# Multithreading in Julia

**URL:** <https://discourse.julialang.org/t/multithreading-in-julia/3579>\
**Category:** General Usage\
**Tags:** multithreading\
**Created:** [May 7, 2017, 4:27pm UTC](https://discourse.julialang.org/t/multithreading-in-julia/3579 "2017-05-07T16:27:37Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Divyansh\_Srivastava](https://avatars.discourse-cdn.com/v4/letter/d/cc9497/32.png) [@Divyansh\_Srivastava](https://discourse.julialang.org/u/Divyansh_Srivastava)\
**Post date:** [May 7, 2017, 4:27pm UTC](https://discourse.julialang.org/t/multithreading-in-julia/3579/1 "2017-05-07T16:27:37Z")

</div>

> a = Threads.Atomic{Int}(0);  
> b = zeros(10)  
> Threads.@threads for i = 1:10  
>  a += i  
>  b[i] = Threads.threadid()  
> end  
> a

When running this code with multiple threads , the value of variable “a” at the end of every iteration is different, certainly less than 55 though. I am unable to understand how exactly is Atomic working here.

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [May 7, 2017, 4:35pm UTC](https://discourse.julialang.org/t/multithreading-in-julia/3579/2 "2017-05-07T16:35:30Z")

</div>

(Please quote your code)

Atomic variable does not mean multiple modification on them will be magically atomic, it only means that every single operations on them are atomic and also obey certain ordering guarantees. In this case `a[] += i` is not a single operation, it is an atomic load, an add, and an atomic store. If you need atomic read-modify-write (RMW), you must use the corresponding functions in `Threads`. (In this case I believe it’s `Threads.atomic_add!()`).

Also note that this code will be slower than single threaded version by a huge factor. (So only good for testing).

---

<div class="post-metadata">

**Author:** ![Divyansh\_Srivastava](https://avatars.discourse-cdn.com/v4/letter/d/cc9497/32.png) [@Divyansh\_Srivastava](https://discourse.julialang.org/u/Divyansh_Srivastava)\
**Post date:** [May 7, 2017, 5:13pm UTC](https://discourse.julialang.org/t/multithreading-in-julia/3579/3 "2017-05-07T17:13:28Z")

</div>

Thanks, I got this working

---

<div class="post-metadata">

**Author:** ![vchuravy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vchuravy/32/8_2.png) [@vchuravy](https://discourse.julialang.org/u/vchuravy)\
**Post date:** [May 8, 2017, 1:25am UTC](https://discourse.julialang.org/t/multithreading-in-julia/3579/4 "2017-05-08T01:25:22Z")

</div>

A post was split to a new topic: [Global variables as thread local storage](https://discourse.julialang.org/t/global-variables-as-thread-local-storage/3587)
