API
The package exports nothing. The schedulers that run OhMyThreads.jl's tforeach, tmapreduce, tmap, @tasks, ... on the team, TeamScheduler and GreedyTeamScheduler, are part of OhMyThreads.jl; see the OhMyThreads.jl documentation.
Parallel loops
ThreadTeams.foreach_chunk — Function
ThreadTeams.foreach_chunk(f, m::Int, p::Int = ThreadTeams.nworkers())Call f(c) for every c in 1:m, each once, on at most min(p, m, nworkers()) threads at a time, the calling task being one of them. With as many chunks as threads, chunk c goes to the c-th participant (as with ThreadTeams.StaticSchedule); with more, participant c starts with chunk c, then the participants take the others from a shared counter until none are left (as with ThreadTeams.GreedySchedule). f decides what a chunk is, e.g. the iterations (c - 1) * n ÷ m + 1:c * n ÷ m of a loop of n.
Runs every chunk serially on the calling task, in order, when the team is busy (held by another task), when the call is nested in a team loop, while a Threads.@threads loop runs, during precompilation, and when m ≤ 1 or p == 1: never on spawned tasks (like busy = :serial).
Chunks that run at the same time never share a thread; a chunk runs on one thread unless it yields. Chunks run in the caller's dynamic scope and world age. If chunks throw, the exception of the lowest failing chunk is rethrown once the chunks already started have finished: every chunk before it runs, and the counter hands out no chunk after the failure is noticed.
The region code is compiled once per type of f. For a concrete type S, precompile(ThreadTeams.foreach_chunk, (S, Int, Int)) compiles all of it but the body of the workers' closure, which the first loop compiles when it creates the closure (a few milliseconds per type, against a few hundred without the statement).
ThreadTeams.foreach_range — Function
ThreadTeams.foreach_range(f, n::Integer; threads::Integer = ThreadTeams.nworkers(),
schedule::Symbol = :static, grain::Integer = 0, isolate::Bool = false)Call f(first, last) on disjoint, nonempty inclusive ranges covering 1:n exactly once. No calls for n == 0. Uses at most p = min(threads, n, nworkers()) participants, capped at 1,048,574 on 64-bit systems and 510 on 32-bit systems.
Split 1:n into balanced contiguous blocks: with q, r = divrem(n, p), the first r blocks have q + 1 indices and the rest have q. Block k belongs to pool worker k, thread Threads.threadpooltids(:default)[k], independent of the caller. A caller on worker k ≤ p runs block k; other callers wait. The caller may rescue a worker's block if it stays awake without claiming its command for a few microseconds, or misses a startup deadline of roughly a millisecond (longer for larger teams). Rescued participants are counted by ThreadTeams.stolen_chunks().
schedule = :static(default): one call per block, for balanced work.schedule = :steal: owners claim ranges from their block's front; idle participants steal from other blocks' tails. Unstarted blocks get the same startup protection as above. This balances uneven work, but execution placement depends on timing: a stalled owner can lose most of its remaining block. Already running calls cannot be stolen. On Linux with Julia ≥ 1.11, when each worker is pinned to a CPU of its own, participants prefer victims sharing their last-level cache, then their NUMA node, and steal from other nodes only once their node seems out of work; otherwise they try victims in cyclic order.grainbounds each call's range length;0currently selects an eighth of a block. Forn ≥ 2^31it runs in static mode, ignoringgrain.
Fixed ownership matches the preferred placement of Threads.@threads :static for the same n and p. NUMA first-touch locality also requires thread affinity (e.g. ThreadPinning.pinthreads(:cores) or :numa). Pin before the first parallel loop, or call ThreadTeams.shutdown!() after pinning: the topology is read when the workers start. Rescue, stealing, serial fallback and migration of a non-sticky caller after a yield can change execution placement.
For nonempty input, run f(1, n) serially on the caller when p == 1, the team is busy, the call is nested in a team loop, a Threads.@threads loop is active, or during precompilation. This ignores placement, schedule and grain; threads = 1 does not select worker 1.
While it waits for the other participants, the caller lets tasks queued on its thread run, as Threads.@threads does. With isolate = true it runs no other task between its own calls of f (it spins and parks its thread instead, and may still rescue blocks): tasks queued on its thread wait for the loop to end. This keeps the caller on its thread and the thread's state as the caller left it, e.g. an interrupt deferred with disable_sigint: Julia up to 1.13 delivers it to whichever task runs on thread 1 next, which could be another task or a worker, and the caller would never see it. This holds only while f does not yield: a call that does lets other tasks run, and may move the caller to another thread.
Calls run in the caller's dynamic scope and world age. Concurrent calls do not share a thread unless they yield. After a failure, participants stop once they observe it; concurrent calls may still start. All started calls finish before the first recorded exception is rethrown, with its backtrace in a ChunkFailedException below it on the exception stack. There is no completed prefix guarantee.
n must be in 0:(typemax(Int) >> 2), threads ≥ 1, and grain ≥ 0; nonzero grain requires schedule = :steal. For concrete S, precompile(ThreadTeams.foreach_range, (S, Int)) compiles both modes except the workers' closure body (see foreach_chunk) and the keyword sorter.
x = Vector{Float64}(undef, 10^8)
ThreadTeams.foreach_range(length(x)) do lo, hi
fill!(view(x, lo:hi), 0.0)
end
ThreadTeams.foreach_range(length(x); schedule = :steal) do lo, hi
for i in lo:hi
x[i] = work(i)
end
endThreadTeams.run_chunks — Function
ThreadTeams.run_chunks(f, n::Int, schedule = ThreadTeams.StaticSchedule())Call f(c) for every c in 1:n, each once: in parallel on the worker pool if it is free, serially (in order, on the calling task) if the call is nested in a parallel operation on the pool or made during precompilation, and on Threads.@spawned tasks (or serially, with busy = :serial) if another task holds the pool. See ThreadTeams.StaticSchedule (which needs n ≤ nworkers()) and ThreadTeams.GreedySchedule.
This is the building block for parallel loops of other packages (OhMyThreads.jl's TeamScheduler and GreedyTeamScheduler are built on it and on ThreadTeams.run_fold); f decides what a chunk is. The region code is compiled for every type of f. With Enzyme.jl loaded it can be differentiated.
ThreadTeams.run_fold — Function
ThreadTeams.run_fold(f, op, n::Int, schedule = ThreadTeams.StaticSchedule())op(op(f(1), f(2)), ...) over 1:n (n ≥ 1) with the f(c) evaluated in parallel as by ThreadTeams.run_chunks and combined in chunk order on the calling task, so op only has to be associative and the result is deterministic for a given n.
ThreadTeams.StaticSchedule — Type
ThreadTeams.StaticSchedule(; busy = :tasks)How ThreadTeams.run_chunks and ThreadTeams.run_fold place the chunks 1:n of a parallel operation on the worker pool: chunk 1 on the calling task and chunk c on worker c, so n must be at most ThreadTeams.nworkers(). The calling task also runs every chunk whose worker has not picked it up in time (asleep, or not scheduled by the OS), so an operation never waits for an idle worker. Lowest overhead; best for balanced chunks.
Only one parallel operation runs on the pool at a time. One started inside a chunk (nested) runs serially. One started while another task uses the pool runs on Threads.@spawned tasks with busy = :tasks (the default), and serially on the calling task with busy = :serial, which also runs the operation serially while a Threads.@threads loop runs (in any task: the check is process-wide). Use :serial in code that is itself run in parallel by tasks or @threads: spreading its loops over threads that are busy already only oversubscribes them. Chunks run in the caller's dynamic scope (ScopedValues, logger) and world age. If chunks throw, the exception of the first failing chunk is rethrown once all started chunks have finished.
Chunks are not guaranteed to run at the same time, nor in tasks of their own: the workers are persistent tasks, so task-local storage outlives an operation.
ThreadTeams.GreedySchedule — Type
ThreadTeams.GreedySchedule(; busy = :tasks)Like ThreadTeams.StaticSchedule, for any number of chunks, with load balancing: the calling task and the workers start with one chunk each, placed as with the static schedule, then take the others from a shared counter until none are left. For chunks that take very different times.
ThreadTeams.runs_serially — Function
ThreadTeams.runs_serially(schedule) -> BoolWhether a parallel operation started now by the calling task with schedule would run serially whatever its number of chunks: with a single thread, inside another parallel operation on the pool, and with busy = :serial while the pool is busy. Callers use it to skip splitting their work. (Operations also run serially during precompilation and, with busy = :serial, inside Threads.@threads, but that is decided later.)
Only plain and relaxed loads, so it can be inlined into the caller.
The team
ThreadTeams — Module
ThreadTeamsA pool of persistent ("parked") worker tasks that runs the chunks of parallel loops with low per-loop overhead, and the scheduling of chunks on it. One sticky worker task runs per thread of the :default thread pool. After a loop, idle workers spin for a short while (see ThreadTeams.set_spin_time!) before they sleep, so back-to-back loops pay for no task creation, scheduling or wake-up.
The package exports nothing. Parallel loops:
ThreadTeams.foreach_chunk: a loop over chunk indices, for callers that split the work themselves;ThreadTeams.foreach_range: a loop over ranges of indices with the placement ofThreads.@threads :static, optionally with work stealing;ThreadTeams.run_chunksandThreadTeams.run_foldwith aThreadTeams.StaticScheduleorThreadTeams.GreedySchedule: the building blocks of theTeamSchedulerandGreedyTeamSchedulerof OhMyThreads.jl, which runstforeach,tmapreduce,tmap,@tasks, ... on the pool.
Pool controls: ThreadTeams.nworkers, ThreadTeams.set_spin_time!, ThreadTeams.spin_time, ThreadTeams.parallel_phase, ThreadTeams.shutdown!.
With Enzyme.jl loaded, parallel operations on the team can be differentiated in forward and reverse mode (a package extension; see the README).
ThreadTeams.nworkers — Function
ThreadTeams.nworkers() -> IntMaximum number of chunks a parallel loop is split into: the number of threads of the :default thread pool (Threads.nthreads(:default)).
ThreadTeams.set_spin_time! — Function
ThreadTeams.set_spin_time!(seconds::Real)Set how long an idle worker busy-waits for the next parallel loop before it sleeps; default 100e-6 (100 µs). The time counts from the end of the loop: a worker that finished early keeps spinning while the loop waits for the other chunks. A worker that the loops do not use counts from the end of its own last chunk, also while other loops run. Takes effect the next time a worker starts waiting.
Longer spinning makes loops that follow each other with short serial gaps cheaper (waking a sleeping worker costs about 10 µs), but idle workers keep their CPU busy for that long after every loop. With 0, workers sleep as soon as they notice the pool is idle, which they check every 64 spins (about 100 ns), so loops closer than that keep them awake (lowest CPU use, highest latency). To spin only during a part of the program, use ThreadTeams.parallel_phase.
On CPUs with performance and efficiency cores (recent Intel, Apple silicon), spinning cores take power and turbo headroom from the busy ones; LLVM's and GCC's OpenMP runtimes do not spin there by default. Consider set_spin_time!(0).
ThreadTeams.spin_time — Function
ThreadTeams.spin_time() -> Float64Current spin time of idle workers in seconds, see set_spin_time!.
ThreadTeams.parallel_phase — Function
ThreadTeams.parallel_phase(f)Call f() and return its result. While f runs, idle workers keep spinning instead of sleeping after spin_time(), and sleeping workers are woken at the start. Use it around a part of the program with many parallel loops separated by serial work longer than the spin time, so that the loops do not pay for waking the workers (about 10 µs each). Idle workers still sleep when their thread has another task to run, but otherwise keep their CPU busy until f returns.
Phases may be nested and may be active in several tasks at once.
ThreadTeams.parallel_phase() do
for step in 1:nsteps
serial_part!(state) # e.g. 1 ms
ThreadTeams.foreach_range(length(u)) do lo, hi
...
end
end
endThreadTeams.shutdown! — Function
ThreadTeams.shutdown!()Stop all worker tasks and drop the pool. Waits for a parallel region running in another task to finish first. The next parallel loop starts a new pool.
Throws an error when called from inside a parallel loop.
ThreadTeams.ChunkFailedException — Type
ThreadTeams.ChunkFailedExceptionThe exception of a chunk that did not run on the calling task: exception, and the raw backtrace of the task that ran it. Like TaskFailedException, it keeps the raw backtrace and only looks up its stack frames when it is shown (CapturedException looks them up when it is created: milliseconds on Julia 1.10 and 1.11).
A loop rethrows the chunk's original exception; the ChunkFailedException is on the exception stack below it (current_exceptions()), shown as "caused by: ...".