MWE:
julia> mutable struct Atomic{T}
@atomic a::T
end
julia> obj1 = Atomic(collect(1:4))
Atomic{Vector{Int64}}([1, 2, 3, 4])
julia> obj1.a .= 2
4-element Vector{Int64}:
2
2
2
2
Unlike directly changing the field itself (@atomic obj1.a = [2,2,2,2]
), it seems that this operation does not require the macro annotation. I wonder if doing this is also thread-safe? I would guess it’s not, since obj1.a
itself is just a Vector
referenced by obj1
. As we perform element-wise mutation, we are no longer modifying obj1
, but rather interacting directly with obj1.a
.
If that’s the case, is there a way to automatically make a container-type (e.g., Array
) object thread-safe using atomic formalism? Or is the only way to do it just to apply a lock? For instance:
function safely_set!(box::AbstractArray{T, N}, val::T) where {T, N}
lk = ReentrantLock()
lock(lk) do
box .= val
end
box
end
Thanks!!