Mutable object in parallel loop

Hello,

Let’s say that I have a type Foo which is mutable and assume that the construction of an instance of Foo is quite long. I also have a function set_state(foo::Foo, bar::Vector{Float64}).

Here is a sequential example of what I want to achieve

function average_value(foo::Foo, n::Int)
    total = 0
    for k in 1:n
        set_state(foo, rand(10))
        total += compute_value(foo)
    end
    total / n    
end

where compute_value initialize some internal variables to a given value, update them according to the randomly generated state and return the a function of those variables. This should work perfectly fine for sequential code since the variables are reset at each instance of the loop.

What happen if I use a parallel loop instead? That’s it, I run

function average_value(foo::Foo, n::Int)
    @everywhere total = 0
    @parallel for k in 1:n
        set_state(foo, rand(10))
        total += compute_value(foo)
    end
    total / n    
end

Do I need to copy foo to prevent it from being updated by multiple workers at the same time or is everything already taken care of by Julia?

Yes, you need to handle this.