# How to preallocate for a parallel monte carlo simulation?

**URL:** <https://discourse.julialang.org/t/how-to-preallocate-for-a-parallel-monte-carlo-simulation/107104>\
**Category:** New to Julia\
**Tags:** parallel, optimization, monte-carlo, channel, preallocation\
**Created:** [December 4, 2023, 10:43am UTC](https://discourse.julialang.org/t/how-to-preallocate-for-a-parallel-monte-carlo-simulation/107104 "2023-12-04T10:43:29Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![mlanghinrichs](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mlanghinrichs/32/50371_2.png) [@mlanghinrichs](https://discourse.julialang.org/u/mlanghinrichs)\
**Post date:** [December 4, 2023, 2:57pm UTC](https://discourse.julialang.org/t/how-to-preallocate-for-a-parallel-monte-carlo-simulation/107104/5 "2023-12-04T14:57:48Z")

</div>

Had a possibly similar need before, and ended up using [FLoops.jl](https://github.com/JuliaFolds/FLoops.jl) which I can recommend. Maybe see also my own [question](https://discourse.julialang.org/t/how-to-implement-multi-threading-with-external-in-place-mutable-variables/62610/1) a while ago.

I use the following pattern, maybe it’s useful in your case? I think your `work_vector` could be `varexternal` below.

```julia
using FLoops

ex = ThreadedEx() # or SequentialEx()

@floop ex for i = 1:nparticles
    @init ve = deepcopy(varexternal)

    # compute something by f, potentially using external variables ve
    # (each thread base has its "own" ve; ve can be mutated in-place)
    out[i] = f(ve)
end

```

---

_[View the full topic](https://discourse.julialang.org/t/how-to-preallocate-for-a-parallel-monte-carlo-simulation/107104)._
