# Is it possibly to do atomic update on an array element?

**URL:** https://discourse.julialang.org/t/is-it-possibly-to-do-atomic-update-on-an-array-element/112113
**Category:** General Usage
**Created:** [March 26, 2024, 12:43am UTC](https://discourse.julialang.org/t/is-it-possibly-to-do-atomic-update-on-an-array-element/112113 "2024-03-26T00:43:07Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)
#### Post date: [March 26, 2024, 1:32am UTC](https://discourse.julialang.org/t/is-it-possibly-to-do-atomic-update-on-an-array-element/112113/4 "2024-03-26T01:32:32Z")

</div>

An unclean way would be to add a lock to the special type in the array. Something like:

```julia
mutable struct NewAtomicMutable
    lck::ReentrantLock
    a::Int
    b::Int
end

cvec = [NewAtomicMutable(Base.ReentrantLock(), 0, 0) for _ in 1:5]

for i in 1:10
    idx = rand(eachindex(cvec))
    lock(cvec[idx].lck)
    try
        cvec[idx].a += 1
        cvec[idx].b += 2
    finally
        unlock(cvec[idx].lck)
    end
end

```

The last loop atomically modifies the data fields of the mutable struct.  
This is not very clean, and can be abstracted to a new Array type. Perhaps someone knows about an existing implementation (sounds like a construct which would in occasional use).

Actually, for strictly update operations, a SpinLock might be more performant:

```julia
mutable struct NewAtomicSpin
    lck::Base.Threads.SpinLock
    a::Int
    b::Int
end

cvec = [NewAtomicSpin(Base.Threads.SpinLock(), 0, 0) for _ in 1:5]

```

(can be used with the same update loop)

---

_[View the full topic](https://discourse.julialang.org/t/is-it-possibly-to-do-atomic-update-on-an-array-element/112113)._
