Skip to content

Commit 09c2a53

Browse files
author
Michael Abbott
committed
threaded map with Threads.spawn
1 parent 5f71649 commit 09c2a53

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

src/SliceMap.jl

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,10 @@ end
276276
threadmap(f, A)
277277
threadmap(f, A, B)
278278
279-
Simple version of `map` using a `Threads.@threads` loop;
280-
only for vectors & really at most two of them, of nonzero length,
279+
Simple version of `map` using a `Threads.@threads` loop,
280+
or `Threads.@spawn` on Julia >= 1.3.
281+
282+
Only for vectors & really at most two of them, of nonzero length,
281283
with all outputs having the same type.
282284
"""
283285
function threadmap(f::Function, vw::AbstractVector...)
@@ -286,14 +288,32 @@ function threadmap(f::Function, vw::AbstractVector...)
286288
out1 = f(first.(vw)...)
287289
_threadmap(out1, f, vw...)
288290
end
289-
# NB barrier
290-
function _threadmap(out1, f, vw...)
291-
out = Vector{typeof(out1)}(undef, length(first(vw)))
292-
out[1] = out1
293-
Threads.@threads for i=2:length(first(vw))
294-
@inbounds out[i] = f(getindex.(vw, i)...)
291+
# NB function barrier. Plus two versions:
292+
@static if VERSION >= v"1.3"
293+
294+
function _threadmap(out1, f, vw...)
295+
out = Vector{typeof(out1)}(undef, length(first(vw)))
296+
out[1] = out1
297+
Threads.@threads for i in 2:length(first(vw))
298+
@inbounds out[i] = f(getindex.(vw, i)...)
299+
end
300+
out
301+
end
302+
303+
else
304+
305+
function _threadmap(out1, f, vw...)
306+
ell = length(first(vw))
307+
out = Vector{typeof(out1)}(undef, ell)
308+
out[1] = out1
309+
Base.@sync for is in Iterators.partition(2:ell, div(ell, Threads.nthreads()))
310+
Threads.@spawn for i in is
311+
@inbounds out[i] = f(getindex.(vw, i)...)
312+
end
313+
end
314+
out
295315
end
296-
out
316+
297317
end
298318

299319
# Collect generators to allow indexing

0 commit comments

Comments
 (0)