Warm tip: This article is reproduced from serverfault.com, please click

asynchronous-朱莉娅:@sync不会将控制权传递给朱莉娅函数的其余部分

(asynchronous - Julia: @sync not passing control to the rest of the Julia function)

发布于 2020-12-07 15:15:48

我想了解Julia中@sync和@async宏的用法。我正在尝试使此MWE正常工作,并且程序不会终止。任何帮助表示赞赏。

function process_node(nodes, id)
    @show id
    sleep(1.0)
    nodes[id] = true 
    return
end 

function main() 
    nodes = Dict( i => false for i in 1:10 )
    jobs = Channel{Int}(15)
    for i in 1:10 
        put!(jobs, i)
    end 
    @sync for id in jobs
        @async process_node(nodes, id)
    end 
    println("done")
end 


main()

程序永远不会上线println("done")我不知道为什么。

提前致谢。

Questioner
user62089
Viewed
11
attdona 2020-12-08 01:57:58

在此示例中,使用@sync没有错@async

循环for id in jobs永远不会返回,因为它会永远阻止无休止地等待不再插入Channel的值。

直接从文档

返回的Channel可以用作for循环中的可迭代对象,在这种情况下,循环变量采用所有产生的>值。通道关闭时,循环终止。

一种解决方案是用一个特殊Int来表示值流的末尾,例如,-1或者用一个nothing不可能,则声明jobsChannel{Union{Int, Nothing}}

function main() 
    nodes = Dict( i => false for i in 1:10 )
    jobs = Channel{Int}(15)
    for i in 1:10 
        put!(jobs, i)
    end 
    put!(jobs, -1)

    @sync for id in jobs
        if id == -1
            close(jobs)
        else
            @async process_node(nodes, id)
        end
        
    end
    
    println("done")
end