Reputation: 626
How to prevent using global array in iterations in the module?
module Mod
global AAA=Array{Float64,1}(undef, 999999999)
for i in 1:100
f(AAA, AAAupdate) # function f take in AAA, update it and output the updated array as AAAupdate
g(AAAupdate,AAA) # function g take in the updatedAAA, and update it again to make a new AAA, and output the new AAA as AAA.
end
end
As we can see, for each i loop,
the big array AAA first need to be input to function f, then updated to AAAupdate.
then function g takein the AAAupdate array, and further update it and form an updated array AAA.
Then in the next loop, the newly updated AAA will be read in function f again, and the process repeat 100 times.
Finally, after the 100 loops, AAA will be completely updated.
In this case, again since Julia discourages global stuff, are there ways to prevent making AAA a global array?
Upvotes: 1
Views: 67
Reputation: 2301
it's fine to use global stuff if your entire module can only do one calculation at a time.
The traditional solution is to put that array into the same function where for
loop is called:
function do_MC(L)
AAA = Vector......
AAA_up = similar(AAA)
for i = 1:L
f!(AAA, AAA_up)
g!(AAA_up, AAA)
end
return AAA
end
But a global is fine speed-wise as long as you:
const AAA=Array{Float64,1}(undef, 999999999)
But here are two questions for you:
for
loop in parallel.Upvotes: 2
Reputation: 13800
I will cross-post my answer from Discourse, which essnetially implements the first paragraph of Jerry's answer:
julia> function main()
AAA = zeros(5)
for i ∈ 1:2
f!(AAA)
g!(AAA)
end
return AAA
end
main (generic function with 1 method)
julia> main()
5-element Vector{Float64}:
12.0
12.0
12.0
12.0
12.0
Upvotes: 2