朱莉娅-是否可以在for循环中使用进度条和Threads。@ threads?

时间:2019-06-14 13:27:10

标签: for-loop parallel-processing progress-bar julia

假设我有这个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循环和进度条中具有并行性?

1 个答案:

答案 0 :(得分:1)

这段代码很好用:

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[])