# Help with shared arrays

**URL:** <https://discourse.julialang.org/t/help-with-shared-arrays/125233>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 26, 2025, 4:49pm UTC](https://discourse.julialang.org/t/help-with-shared-arrays/125233 "2025-01-26T16:49:15Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![Fernando1](https://avatars.discourse-cdn.com/v4/letter/f/22d042/32.png) [@Fernando1](https://discourse.julialang.org/u/Fernando1)\
**Post date:** [February 8, 2025, 7:10pm UTC](https://discourse.julialang.org/t/help-with-shared-arrays/125233/5 "2025-02-08T19:10:46Z")

</div>

Hi all, this is the same post as I had done before but with the code correctly added.

I am trying to run a “Simulate” function living in a separate module and extract the states from it with a getStates function. The idea is that I launch the sim to  
a parallel process and get the states after some time through a SharedArray.

When I create this script:

```julia
using Distributed
using SharedArrays

include("Simulations.jl")
using .Simulations
# Add workers (processes)
if nprocs() == 1 # Ensure at least one worker is added
    addprocs(2) # Add 2 worker processes
end

# SharedArray to hold the states
@everywhere using SharedArrays 
states = SharedArray{Float64}(1)
states[1] = 1.0 

function startSim()
    worker_id = 2 # Choose the worker where the task will run
    @spawnat worker_id Simulations.Simulate(states)
end

function getStates()
    return states[1]
end

# Start the HTTP server
println("Starting sim")

startSim()

sleep(1)

s = getStates();

println("States after aprox 1 second:", s)

```

where:

```julia
module Simulations
using SharedArrays 
# Simulate function
function Simulate(states::SharedArray)
    for i in 1:1000
        states[1] = states[1] - 0.002 * states[1]
        sleep(0.01)
    end
end
end

```

It doesn’t update. However if instead of including the module I declare Simulate function inside the main script it works:

```julia
using Distributed
using SharedArrays

# Add workers (processes)
if nprocs() == 1 # Ensure at least one worker is added
    addprocs(2) # Add 2 worker processes
end

# SharedArray to hold the states
@everywhere using SharedArrays 
states = SharedArray{Float64}(1)
states[1] = 1.0 

# Simulate function
@everywhere function Simulate(states::SharedArray)
    for i in 1:1000
        states[1] = states[1] - 0.002 * states[1]
        sleep(0.01)
    end
end

function startSim()
    worker_id = 2 # Choose the worker where the task will run
    @spawnat worker_id Simulate(states)
end

function getStates()
    return states[1]
end

# Start the HTTP server
println("Starting sim")

startSim()

sleep(1)

s = getStates();

println("States after aprox 1 second:", s)

```

I don’t know what I am doing wrong. I’d be very grateful if someone could give me a help.

Thank you!

---

_[View the full topic](https://discourse.julialang.org/t/help-with-shared-arrays/125233)._
