Why can't I modify the array in place when changing the type of array?

Hello, consider the following example:

julia> using SharedArrays

julia> function foo1(a::SharedArray)
       fill!(a, 4.0)
       end
foo1 (generic function with 1 method)

julia> function foo2(a::AbstractArray)
       a = SharedArray(a)
       foo1(a)
       end
foo2 (generic function with 1 method)

julia> a1 = SharedArray{Float64}(5, 5);

julia> a2 = Array{Float64}(undef, 5, 5);

julia> foo1(a1);

julia> a1
5×5 SharedArray{Float64,2}:
 4.0  4.0  4.0  4.0  4.0
 4.0  4.0  4.0  4.0  4.0
 4.0  4.0  4.0  4.0  4.0
 4.0  4.0  4.0  4.0  4.0
 4.0  4.0  4.0  4.0  4.0

julia> foo2(a2);

julia> a2
5×5 Array{Float64,2}:
 2.3586e-314   2.35848e-314  2.33899e-314  2.33899e-314  2.33899e-314
 2.35897e-314  2.359e-314    2.33899e-314  2.33899e-314  2.33899e-314
 2.35872e-314  2.359e-314    2.33899e-314  2.33899e-314  2.33899e-314
 2.35844e-314  2.35848e-314  2.33899e-314  2.33899e-314  2.33899e-314
 2.3588e-314   2.35848e-314  2.33899e-314  2.33899e-314  2.33899e-314

I thought foo2 would give the modified array instead of the undef one since I overwrite the array with the new one in the function. Is it due to that I can only change the element value but cannot change the type of the array (from a usual array to SharedArray) in such case? Thanks in advance.

Not at a computer, so I can’t test, but I think your a = SharedArray(a) in foo2 is assigning a new local variable a inside the function scope rather than updating the global a assignment. If you put a global in front of it, I think it will work, but that’s not really changing it “in place,” just reassigning the variable to a new array.

I might also be full of crap - it’s late and I probably should be asleep :neutral_face:

1 Like

SharedArray(a) copies a into the SharedArray.

2 Likes