朱莉娅:早点从pmap返回()

时间:2017-11-30 01:52:28

标签: parallel-processing julia

说我有以下内容:

function f(x)
  some_test ? true : false
end

如果我pmap(f,some_array),我会得到一些Bools。如果contains(==,p,false),我想做点什么。但是,如果至少只有一个false,我想做这件事。即如果some_array非常大,我希望pmap在找到第一个false时停止。

some_test可能非常复杂,所以我读过并行for循环不是可行的方法。

如果我有

p = pmap(f,some_array,[N for i = 1:some_large_value])
if contains(==,p,false)
    return false
else
    return true
end

并在false时显示i=100,如何阻止pmap检查101:some_large_value

作为我想做的行为的另一个例子,请从?pmap获取此示例。

julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=ex->0)
4-element Array{Int64,1}:
 1
 0
 3
 0

而不是on_error=ex->0我想在第一个偶数上pmapreturn。像

这样的东西
pmap(x->iseven(x) ? return : x, 1:4)

理想情况下只会产生1-element Array{Int64,1}

1 个答案:

答案 0 :(得分:0)

这通常很难做到,因为其他任务可能已经开始。如果你不担心做一些额外的运行,一种方法是修改parallel computing docs

中的pmap示例
function pmap_chk(f, lst)
    np = nprocs()  # determine the number of processes available
    n = length(lst)
    results = Vector{Any}(n)

    i = 0
    nextidx() = (i+=1; i)

    done = false
    isdone() = done
    setdone(flag) = (done = flag)

    @sync begin
        for p=1:np
            if p != myid() || np == 1
                @async begin
                    while !isdone()
                        idx = nextidx()
                        if idx > n
                            break
                        end
                        r, flag = remotecall_fetch(f, p, lst[idx])
                        results[idx] = r
                        if flag
                            setdone(flag)
                        end
                    end
                end
            end
        end
    end
    resize!(results, i)
end

这里f应该返回一个包含结果的元组以及它是否完成,例如

julia> pmap_chk(1:100) do f
       r = rand()
       sleep(r)
       (r, r>0.9)
       end
15-element Array{Any,1}:
 0.197364 
 0.60551  
 0.794526 
 0.105827 
 0.612087 
 0.170032 
 0.8584   
 0.533681 
 0.46603  
 0.901562 
 0.0894842
 0.718619 
 0.501523 
 0.407671 
 0.514958 

请注意,它不会立即停止。