我如何在 Julia 中以非交互方式执行 I/O 循环 运行?

How do I do I/O in Julia distributed for loop run non-interactively?

foo.jl中使用以下代码:

using Distributed

@distributed for k = 1:4
    println("Creating file ", k)
    write(string("file_", k), "foo")
end

在 REPL 中执行 include("foo.jl") 会打印预期的行并创建预期的文件,但是当我退出 REPL 并且 运行

julia foo.jl

没有写入任何文件,也没有创建文件。

为什么会有差异,脚本需要什么才能在 REPL 之外达到预期的 运行?

@distributed 没有阻塞,因此 Julia 进程在写入任何文件之前完成。尝试

using Distributed

@sync @distributed for k = 1:4
    println("Creating file ", k)
    write(string("file_", k), "foo")
end

相反。

documentation 中所述:

Note that without a reducer function, @distributed executes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with @sync

在您的情况下(不使用 reducer 函数),会发生这种情况:@distributed 生成任务并立即 returns。您的任务非常短,以至于在 REPL 中您几乎可以立即看到它们,并且不会真正注意到与同步过程的区别(除了可能输出与 REPL 提示混合)。

然而,在脚本中,julia 主进程在生成任务后立即终止,没有任何机会实际 运行 它们。而且您看不到输出。

根据文档的建议,使用 @sync 等待任务完成,然后再存在:

using Distributed

@sync @distributed for k = 1:4
    println("Creating file ", k)
    write(string("file_", k), "foo")
end