Variable scope in julia tasks

I adapted the pmap () implementation for my program to do some planning, and I have a question about the scope of variables in tasks. This is the implementation of 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 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 replaced the line idx = nextidx () with idx = x; i = i + 1 ;, each task updates its local copy of variable i. However, the variable i inside the nextidx () function is shared by all tasks. Why is this?

+4
source share
1 answer

Let me simplify the above code first:

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 .

0

All Articles