朱莉娅 - 是否可以在相同的 for 循环中使用进度条和Threads.@threads



>假设我有这个 for 循环:

for i in 1:100000
   1+1 
   # Let's do some long computations here
end

这两个 for 循环工作:

Threads.@threads for i in 1:100000
   1+1 
   # Let's do some long computations here
end
using ProgressMeter
@showprogress 1 "Computing..." for i in 1:100000
   1+1 
   # Let's do some long computations here
end

但以下方法均无效:

@showprogress 1 "Computing..." Threads.@threads for i in 1:100000
   1+1 
   # Let's do some long computations here
end
using ProgressMeter
Threads.@threads @showprogress 1 "Computing..." for i in 1:100000
   1+1 
   # Let's do some long computations here
end

那么在 Julia 中是否有可能在 for 循环和进度条中具有并行性?

这段代码很好用:

using ProgressMeter
N = 200
p = Progress(N);
update!(p,0)
jj = Threads.Atomic{Int}(0)
l = Threads.SpinLock()
Threads.@threads for i in 1:N
   sum(rand(10_000_000)) # some big computation
   Threads.atomic_add!(jj, 1)
   Threads.lock(l)
   update!(p, jj[])
   Threads.unlock(l)  
end

如果您不想使用锁,您也可以考虑仅在第一个线程上更新(但是在这种情况下,进度条运行不太流畅(:

Threads.threadid() == 1 && update!(p, jj[])

相关内容

最新更新