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