【问题标题】:Parallel Processing for nested loops in JuliaJulia 中嵌套循环的并行处理
【发布时间】:2020-12-18 04:23:38
【问题描述】:

我正在尝试为嵌套循环实现并行处理。但是我收到以下语法错误。

我正在从这里修改示例 (Parallel computing in Julia - running a simple for-loop on multiple cores)

这行得通

for N in 1:5:20, H in 1:5:20
           println("The N of this iteration in $N, $H")
end

这是语法错误

using Distributed

@distributed for N in 1:5:20, H in 1:5:20
           println("The N of this iteration in $N, $H")
       end

【问题讨论】:

    标签: julia


    【解决方案1】:

    @distributed 宏仅支持迭代一个参数。因此你可以这样做:

    @distributed for (N,H) in collect(Iterators.product(1:5:20,1:5:20))
        println("The N of this iteration in $N, $H")
    end
    

    另一个选项当然是嵌套循环。在这种情况下,只有一个循环应该是@distributed

    【讨论】:

      【解决方案2】:

      另一种选择(对于单节点,多核并行化)是多线程。由于较低的开销和共享内存,这通常更容易/更有效(请注意,在 Julia 中没有 Python GIL 之类的东西)。 对应的 Julia 命令是 Threads.@threads(在 for 循环前面)或 Threads.@spawn,用于生成要并行执行的任务。

      编辑:添加示例

      Threads.@threads for (N,H) in collect(Iterators.product(1:5:20,1:5:20))
          println("The N of this iteration in $N, $H")
      end
      

      第二种情况:

      f(x) = x^2
      futures = [Threads.@spawn f(x) for x=1:10]
      fetch.(futures)
      

      【讨论】:

      • 你能提供一个可重现的例子吗?
      • 上面添加的示例
      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多