朱莉娅任务中的可变范围
variable scope in julia tasks
我已将 pmap() 实现应用到我的程序中以进行一些调度,但我对任务中变量的范围有疑问。这是 Julia 实现
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
如果我用 idx=x 替换行 idx = nextidx();我=我+1; ,每个任务更新其变量 i 的本地副本。然而,函数 nextidx() 中的变量 i 由所有任务共享。这是为什么?
我先把上面的代码简化一下:
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
我们在声明 i
的同一过程中声明 nexti()
,并且 nexti()
中的 i
指的是相同的位置,因此对 [=12 的任何更改=] inside nexti()
alerts i
value in outer scope.
另一方面,@async 宏强制内部块,在不同的进程上 运行 因此该块使用 i
值的副本,并且该块内的任何更改都不会提醒 i
外部范围内的值。
我已将 pmap() 实现应用到我的程序中以进行一些调度,但我对任务中变量的范围有疑问。这是 Julia 实现
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
如果我用 idx=x 替换行 idx = nextidx();我=我+1; ,每个任务更新其变量 i 的本地副本。然而,函数 nextidx() 中的变量 i 由所有任务共享。这是为什么?
我先把上面的代码简化一下:
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
我们在声明 i
的同一过程中声明 nexti()
,并且 nexti()
中的 i
指的是相同的位置,因此对 [=12 的任何更改=] inside nexti()
alerts i
value in outer scope.
另一方面,@async 宏强制内部块,在不同的进程上 运行 因此该块使用 i
值的副本,并且该块内的任何更改都不会提醒 i
外部范围内的值。