Trying to use ProgressMeter.jl
for simple multi-threaded loops, I came up with the following. I am surprised that this works, since I usually get error messages when I try to print anything from inside a @threads for
. So I ask (1) is what I am doing actually “ok” (i.e., correct, safe, …); and (2) why can ProgressMeter
print from within the loop?
module MtProgress
using ProgressMeter, Base.Threads
function mysleep(t)
t0 = time_ns()
while (time_ns() - t0) * 1e-9 < t
nothing
end
end
function workerfun(n)
mysleep(1.0)
return rand()
end
function mt_progress(N)
A = zeros(N)
P = Progress(N)
idx = 0
P_lock = SpinLock()
@threads for n = 1:N
A[n] = workerfun(n)
lock(P_lock)
idx += 1
ProgressMeter.update!(P, idx)
unlock(P_lock)
end
end
end
t1 = time_ns()
MtProgress.mt_progress(30)
println("Elapsed = $((time_ns()-t1)*1e-9)s")