# Mutable object in parallel loop

**URL:** <https://discourse.julialang.org/t/mutable-object-in-parallel-loop/6595>\
**Category:** General Usage\
**Created:** [October 21, 2017, 2:32pm UTC](https://discourse.julialang.org/t/mutable-object-in-parallel-loop/6595 "2017-10-21T14:32:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![maxtremblay](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/maxtremblay/32/1369_2.png) [@maxtremblay](https://discourse.julialang.org/u/maxtremblay)\
**Post date:** [October 21, 2017, 2:32pm UTC](https://discourse.julialang.org/t/mutable-object-in-parallel-loop/6595/1 "2017-10-21T14:32:07Z")

</div>

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

```julia
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

```julia
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?

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [October 21, 2017, 2:50pm UTC](https://discourse.julialang.org/t/mutable-object-in-parallel-loop/6595/2 "2017-10-21T14:50:45Z")

</div>

> [@maxtremblay](#):
>
> 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.
