2015-05-18 67 views
4

我已經調整了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由所有任務共享。爲什麼是這樣?

回答

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宣佈,並inexti()指的是同一個位置,所以裏面nexti()警報ii任何改變在外部範圍內的價值。

另一方面,@async宏強制內部的塊,在不同的進程上運行,因此此塊使用值爲i的副本,並且此塊內的任何更改都不會在外部範圍內提示i值。