# Your friendly neighbourhood multithreaded Spiderman

**URL:** <https://discourse.julialang.org/t/your-friendly-neighbourhood-multithreaded-spiderman/31560>\
**Category:** New to Julia\
**Created:** [November 27, 2019, 7:13am UTC](https://discourse.julialang.org/t/your-friendly-neighbourhood-multithreaded-spiderman/31560 "2019-11-27T07:13:49Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![StevenSiew](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevensiew/32/218393_2.png) [@StevenSiew](https://discourse.julialang.org/u/StevenSiew)\
**Post date:** [November 27, 2019, 7:13am UTC](https://discourse.julialang.org/t/your-friendly-neighbourhood-multithreaded-spiderman/31560/1 "2019-11-27T07:13:49Z")

</div>

Hi I am your friendly neighborhood multithreaded spiderman

Today, you have gain a new superpower with your new suit called julia-1.3

Before you go swinging high above the building tops, I want to talk about thread safety.

Let’s jump straight into thread safety

UNSAFE THREAD USAGE

```julia
julia> using Base.Threads

julia> total=0
0

julia> Threads.@threads for k = 1:1_000_000
                global total += 1
         end

julia> total
170321

```

Opps, instead of one million, we only get 170321. You may think that is because the variable total is not thread safe. So let’s use an atomic powered variable

STILL UNSAFE THREAD USAGE

```julia
julia> using Base.Threads

julia> atomic_total = Threads.Atomic{Int}(0)
Atomic{Int64}(0)

julia> Threads.@threads for k = 1:1_000_000
                global atomic_total[] = atomic_total[] + 1
          end

julia> atomic_total[]
144247

```

Wow! Even atomic powered variable does not provide thread safety. You also need atomic functions

SAFE THREAD USAGE

```julia
julia> using Base.Threads

julia> atomic_total = Threads.Atomic{Int}(0)
Atomic{Int64}(0)

julia> Threads.@threads for k = 1:1_000_000
                       global atomic_total
                       Threads.atomic_add!(atomic_total,1)
          end

julia> atomic_total[]
1000000

```

Yeah now you feel like a million dollars.

Moral of the story: Everytime you swing above the rooftops and your threads depend on something that other threads also depends upon, you need to practise safe threading otherwise you will fall and hurt yourself.
