Skip to content

Commit

Permalink
fix using non zero axes arrays in threads loops (JuliaLang#33396)
Browse files Browse the repository at this point in the history
  • Loading branch information
KristofferC committed Sep 30, 2019
1 parent d036575 commit f696e17
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
4 changes: 2 additions & 2 deletions base/threadingconstructs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function _threadsfor(iter,lbody)
len, rem = 1, 0
end
# compute this thread's iterations
f = 1 + ((tid-1) * len)
f = firstindex(r) + ((tid-1) * len)
l = f + len - 1
# distribute remaining iterations evenly
if rem > 0
Expand All @@ -57,7 +57,7 @@ function _threadsfor(iter,lbody)
end
# run this thread's iterations
for i = f:l
local $(esc(lidx)) = Base.unsafe_getindex(r,i)
local $(esc(lidx)) = @inbounds r[i]
$(esc(lbody))
end
end
Expand Down
36 changes: 20 additions & 16 deletions test/threads_exec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,30 @@ end
# parallel loop with parallel atomic addition
function threaded_loop(a, r, x)
@threads for i in r
a[i] = 1 + atomic_add!(x, 1)
j = i - firstindex(r) + 1
a[j] = 1 + atomic_add!(x, 1)
end
end

function test_threaded_loop_and_atomic_add()
x = Atomic()
a = zeros(Int,10000)
threaded_loop(a,1:10000,x)
found = zeros(Bool,10000)
was_inorder = true
for i=1:length(a)
was_inorder &= a[i]==i
found[a[i]] = true
end
@test x[] == 10000
# Next test checks that all loop iterations ran,
# and were unique (via pigeon-hole principle).
@test !(false in found)
if was_inorder && nthreads() > 1
println(stderr, "Warning: threaded loop executed in order")
for r in [1:10000, collect(1:10000), Base.IdentityUnitRange(-500:500), (1,2,3,4,5,6,7,8,9,10)]
n = length(r)
x = Atomic()
a = zeros(Int, n)
threaded_loop(a,r,x)
found = zeros(Bool,n)
was_inorder = true
for i=1:length(a)
was_inorder &= a[i]==i
found[a[i]] = true
end
@test x[] == n
# Next test checks that all loop iterations ran,
# and were unique (via pigeon-hole principle).
@test !(false in found)
if was_inorder && nthreads() > 1
println(stderr, "Warning: threaded loop executed in order")
end
end
end

Expand Down

0 comments on commit f696e17

Please sign in to comment.