Help with shared arrays - code update

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:

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:

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:

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!

1 Like

Try putting an @everywhere infront of these lines as well and move them below where you create the workers.
In general all workers need to load the code that they are going to run. I am wondering why you didn’t get an error though.

Note that in your example that works you have @everywhere infront of you Simulate function.

1 Like

A post was merged into an existing topic: Help with shared arrays

This worked. Thanks a lot!