# Copy an atomic variable as a regular variable

**URL:** <https://discourse.julialang.org/t/copy-an-atomic-variable-as-a-regular-variable/66117>\
**Category:** General Usage\
**Tags:** multithreading, threads, atomic\
**Created:** [August 10, 2021, 9:29am UTC](https://discourse.julialang.org/t/copy-an-atomic-variable-as-a-regular-variable/66117 "2021-08-10T09:29:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![matthiasbe](https://avatars.discourse-cdn.com/v4/letter/m/5fc32e/32.png) [@matthiasbe](https://discourse.julialang.org/u/matthiasbe)\
**Post date:** [August 10, 2021, 9:29am UTC](https://discourse.julialang.org/t/copy-an-atomic-variable-as-a-regular-variable/66117/1 "2021-08-10T09:29:20Z")

</div>

Hello,

I am trying to read the value of an atomic (shared) variable as a local (on the current thread) variable.

Here is what I tried.

```julia
julia> a = Threads.Atomic{Int}(2)
Base.Threads.Atomic{Int64}(2)

julia> b = convert(Int, a)
ERROR: MethodError: Cannot `convert` an object of type Base.Threads.Atomic{Int64} to an object of type Int64
Closest candidates are:
  convert(::Type{T}, ::T) where T<:Number at number.jl:6
  convert(::Type{T}, ::Number) where T<:Number at number.jl:7
  convert(::Type{T}, ::Base.TwicePrecision) where T<:Number at twiceprecision.jl:250
  ...
Stacktrace:
 [1] top-level scope

```

Do you know how I can snapshot the shared variable to use it locally on the Thread ?  
For more information, I try to do something like [this](https://stackoverflow.com/questions/9363419/greater-than-compare-and-swap).

Have a nice day

---

<div class="post-metadata">

**Author:** ![genkuroki](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/genkuroki/32/18030_2.png) [@genkuroki](https://discourse.julialang.org/u/genkuroki)\
**Post date:** [August 10, 2021, 9:57am UTC](https://discourse.julialang.org/t/copy-an-atomic-variable-as-a-regular-variable/66117/2 "2021-08-10T09:57:38Z")

</div>

Code:

```julia
a = Threads.Atomic{Int}(2)
b = a[]

```

Output:

```julia
2

```

Code:

```julia
using Printf
@show Threads.nthreads()
@show a = Threads.Atomic{Int}(99)
Threads.@threads for i in 1:10
    a[] = i
    @printf "(id: %2d) i = %2d, a[] = %2d\n" Threads.threadid() i a[]
    b = a[]
    @printf "(id: %2d) i = %2d, b = %2d\n" Threads.threadid() i b
end

```

Output:

```julia
Threads.nthreads() = 6
a = Threads.Atomic{Int}(99) = Base.Threads.Atomic{Int64}(99)
(id: 1) i = 1, a[] = 1
(id: 5) i = 9, a[] = 9
(id: 2) i = 3, a[] = 3
(id: 3) i = 5, a[] = 5
(id: 4) i = 7, a[] = 7
(id: 6) i = 10, a[] = 10
(id: 1) i = 1, b = 5
(id: 5) i = 9, b = 5
(id: 2) i = 3, b = 5
(id: 3) i = 5, b = 5
(id: 4) i = 7, b = 5
(id: 6) i = 10, b = 5
(id: 1) i = 2, a[] = 2
(id: 3) i = 6, a[] = 6
(id: 4) i = 8, a[] = 8
(id: 2) i = 4, a[] = 4
(id: 3) i = 6, b = 4
(id: 4) i = 8, b = 4
(id: 1) i = 2, b = 4
(id: 2) i = 4, b = 4

```
