Reputation: 405
I have adapted the pmap() implementation to my program to do some scheduling and I have a question about the scope of the variables within the tasks. This is the Julia implementation
function pmap(f, lst)
np = nprocs() # determine the number of processes available
n = length(lst)
results = cell(n)
i = 1
# function to produce the next work item from the queue.
# in this case it's just an index.
nextidx() = (idx=i; i+=1; idx)
@sync begin
for p=1:np
if p != myid() || np == 1
@async begin
while true
idx = nextidx()
if idx > n
break
end
results[idx] = remotecall_fetch(p, f, lst[idx])
end
end
end
end
end
results
end
If i substitute the line idx = nextidx() by idx=x; i=i+1; , each task updates its local copy of the variable i. However the variable i within the function nextidx() is shared by all the tasks. Why is this?
Upvotes: 4
Views: 315
Reputation: 5746
Let me first simplifies the above code:
function test()
i=10
nexti() = (inx=i;i+=1;inx)
@sync begin
@async begin
i=i+10
nexti()
println("value of i in another thread => $i")
end
end
println("value of i in test() => $i")
end
test()
# value of i in another thread => 20
# value of i in test() => 11
We declare nexti()
in the same process as i
was declared, and i
in nexti()
refers to the same location, so any changes to i
inside nexti()
alerts i
value in outer scope.
On the other hand @async macro forces the block inside, to run on different process so this block use a copy of i
value and any changes inside this block do not alert i
value in outer scope.
Upvotes: 1