Julia:@sync 没有将控制权传递给 Julia 函数的其余部分

Julia: @sync not passing control to the rest of the Julia function

我想了解 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")。不知道为什么。

提前致谢。

在这个例子中使用@sync@async没有错。

循环 for id in jobs 永远不会 return 因为它会永远阻塞,无休止地等待不再插入通道的值。

直接来自 docs:

The returned Channel can be used as an iterable object in a for loop, in which case the loop variable takes on all the produced > values. The loop is terminated when the channel is closed.

一个解决方案是用一个特殊的 Int 值来表示值流的结束,例如 -1 或者如果用 nothing 值这是不可能的,声明jobs 作为 Channel{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