Starting with Julia 1.11 this is available by adding the :greedy switch to @threads as follows:
Threads.@threads :greedy for item in collection
do_the_work(item)
end
However, this doesn’t let you set N; the number of tasks is always Threads.threadpoolsize(). See the documentation for details: Multi-Threading · The Julia Language
To control N, use OhMyThreads.jl instead. Here’s how:
using OhMyThreads
@tasks for item in collection
@set begin
scheduler=:greedy
ntasks=N
end
do_the_work(item)
end
There’s also a macro-free form:
using OhMyThreads
tforeach(collection; scheduler=:greedy, ntasks=N) do item
do_the_work(item)
end