朱莉娅任务中的变量范围

时间:2015-05-18 12:28:30

标签: parallel-processing task julia

我已经将pmap()实现改编为我的程序来进行一些调度,我对任务中变量的范围有疑问。这是朱莉娅的实施

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()行; I = I + 1; ,每个任务更新其变量i的本地副本。但是,函数nextidx()中的变量i由所有任务共享。这是为什么?

1 个答案:

答案 0 :(得分:0)

首先让我简化上面的代码:

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

我们在声明nexti()的同一过程中声明i,而i中的nexti()指的是相同的位置,因此对i的任何更改在nexti()内警告i外部范围内的值。

另一方面,@ async宏强制内部块,在不同进程上运行,因此该块使用i值的副本,此块内的任何更改都不会在外部警告i值范围。