I find if I use Threads.threadid()
and sleep
together, the code will give wrong result. Also give wrong result when I replace sleep
by lock
.
The code shouldn’t output anything, but it did output, that is why I say give wrong result.
Below is my code and output, I run in julia 1.8.5 and by julia --threads 4 xxx.jl
using Base.Threads
lk = ReentrantLock()
n_thread = 4
dat = Array{Int64, 1}(undef, n_thread)
count::Int64 = 0
atom_count = Threads.Atomic{Int64}(0)
for i in 1:4
global count = 0
atom_count[] = 0
fill!(dat, 0)
Threads.@threads for j in 1:100
thread_id = Threads.threadid()
old_num = 0
dat[thread_id] = 0
for k in 1:10
num = rand(1:100)
dat[thread_id] = num
old_num = num
# lock(lk)
# try
# count += 1
# finally
# unlock(lk)
# end
sleep(0.001)
if dat[thread_id] != old_num
println("$thread_id $k")
end
end
Threads.atomic_add!(atom_count, 1)
end
println("=======================")
# while(atom_count[] < 100)
# end
end
=======================
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
=======================
1 1
3 1
3 2
1 2
3 3
1 3
1 4
3 4
1 4
1 5
1 5
3 5
3 6
1 7
1 7
3 7
1 9
3 8
3 9
1 10
3 10
=======================
1 1
2 1
1 2
2 2
1 3
1 4
2 3
1 5
2 4
2 5
1 6
2 6
1 7
1 8
2 7
2 8
1 9
1 10
2 9
2 10
=======================