raskolnikov
raskolnikov

Reputation: 235

Parallel computation in Julia

I'm working with a code in Julia and I'm using parallel computation. Here it is the function I'm using (which is simplified from the real one).

I'm trying to evaluate what I called the "Hitting Time":

using Distributed
using LinearAlgebra


function action(Ntraj::Int64,  
    Tfinal::Float64,                   
    dt::Float64)                
        
    
    # Output time vector
    t = (1 : Ntime) * dt
    
    #Vectors of Hitting Times
    HittingTime = zeros(Ntraj)

    @distributed for ktraj = 1 : Ntraj

        
    HittingTimeBool = false
    

    for jt=1:Ntime
               

            
            if (HittingTimeBool == false && jt >0.1)
                HittingTimeBool=true
                HittingTime[ktraj] = jt*dt
                println(HittingTime[ktraj])
            end
    end
    end
    println(HittingTime)
    return (HittingTime)
end

So I run the function for 5 Trajectories (just to try to see what happens) and these that follows are the results

using Distributed
addprocs(4)

@everywhere include("untitled.jl")

(t, Fid, HittingTime) = @time action(5,10.,0.01);
      From worker 2:    0.01
      From worker 5:    0.01
      From worker 3:    0.01
      From worker 4:    0.01
      From worker 6:    0.01
[0.0, 0.0, 0.0, 0.0, 0.0]
  0.723837 seconds (121.59 k allocations: 6.331 MiB)
HittingTime
5-element Array{Float64,1}:
 0.0
 0.0
 0.0
 0.0
 0.0

As you can see, in the for cycle the function enters the if and the value of HittingTime[ktraj] = jt*dt is stored. But when the for cycle ends, the values in the HittingTime array seems to disappear! I cannot use the hcat as for the FidelitytoTarget since the arrays have different dimensions, so how can I write some code to store these values?

Upvotes: 0

Views: 127

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42244

You need to have a SharedArray to mutate the state across the workers.

using Distributed, SharedArrays
addprocs(4)
HittingTime=SharedArray{Float64}(nworkers())

res = @distributed (+) for i in 1:length(HittingTime)
    HittingTime[i] = rand()
    HittingTime[i]
end

@assert res ≈ sum(HittingTime)

Upvotes: 2

Related Questions