Skip to content

New thread pool - #9734

Draft
abadams wants to merge 16 commits into
abadams/thread_pool_fuzzerfrom
abadams/sticky_threads
Draft

abadams wants to merge 16 commits into
abadams/thread_pool_fuzzerfrom
abadams/sticky_threads

Conversation

@abadams

@abadams abadams commented Nov 30, 2026

Copy link
Copy Markdown
Member

This is a new thread pool implementation. The current one is showing its age, and the speed-ups over it are significant. It does a few things differently:

  • For small jobs (<64 tasks), threads try to claim the same task ID repeatedly. This helps keeps intermediate data resident in back-to-back parallel for loops. This was the main effect that made the gaussian blur slow with the default thread pool. My current CPU has multiple chiplets and moving data between them due to random task assignment is slow.

  • No more sched_yield. We knew this was the wrong thing to do but hadn't figured out how to remove it without a regression. Now we spin using proper pause loops.

  • For simple jobs (i.e. just a normal parallel loop), workers don't acquire the thread pool lock. Each worker gets a handoff slot atomically populated by the thread that enqueues the work. Simple jobs are finalized without workers grabbing the lock too. Main serializes workers both at job start and end, which is catastrophic for tiny jobs. This means workers can't sleep on a condition variable because that needs to grab an associated mutex. Instead I exposed the ability to wait on an address and signal that address from the parking lot, which is how the parking lot works anyway. This could be rebuilt on top of OS primitives (e.g. futex) but doing that showed no appreciable gains and requires separate per-OS implementations. Because each thread waits on its own unique slot, the whole A-team/B-team thing is gone. The right number of threads are just woken. Gaussian blur was launching back-to-back parallel loops of alternating size (e.g. 30 and 31), which was worst-case for the A-team B-team strategy.

  • When a job comes in, threads are woken in a binary tree, where each worker is responsible for waking two others before starting work. This gets everyone working faster than having the owner wake each worker one by one, which is linear in the number of workers even with wake_all broadcasts (the parking lot moves parked threads one by one, and each potentially requires a syscall to wake it up). Multiple strategies were tried (e.g. greedily racing to wake as many workers as possible) but the simple binary tree worked best.

App performance results:

App Manual before (ms) Manual after (ms) Manual speedup Auto before (ms) Auto after (ms) Auto speedup
bgu 3.067 2.235 1.37× 47.23 5.252 8.99×
bilateral_grid 1.102 0.790 1.40× 0.922 0.888 1.04×
camera_pipe 0.355 0.296 1.20× 1.772 1.484 1.19×
compositing 0.595 0.462 1.29× 9.548 9.681 0.99×
conv_layer 1.537 1.498 1.03× 6.371 6.385 1.00×
depthwise_separable_conv 0.329 0.029 11.26× 2.000 1.724 1.16×
harris 0.310 0.278 1.11× 0.564 0.467 1.21×
hist 1.849 0.214 8.66× 15.40 0.641 24.03×
iir_blur 5.892 5.919 1.00× 186.96 84.70 2.21×
interpolate 2.670 2.142 1.25× 17.42 4.847 3.59×
lens_blur 2.018 1.358 1.49× 15.60 1.677 9.30×
local_laplacian 8.114 7.183 1.13× 34.46 13.37 2.58×
max_filter 21.93 22.01 1.00× 25.51 25.65 0.99×
nl_means 13.86 13.86 1.00× 11.10 10.87 1.02×
stencil_chain 3.659 2.173 1.68× 2.373 2.380 1.00×
unsharp 0.671 0.664 1.01× 1.482 1.356 1.09×

The Mullapudi autoscheduler likes tiny parallel tasks and nested parallelism, so it's particularly helpful for it. On Gaussian blur the new thread pool has the same performance as the custom one, so the custom one is deleted.

abadams and others added 11 commits March 13, 2026 12:51
Rewrite the default thread pool so repeated parallel loops map tasks to
the same workers, hand work to workers through per-worker handoff slots,
sleep idle workers with a parking-lot wait-on-address, and wake them in
a binary tree (as oneTBB and LLVM's OpenMP runtime do). Spin with a real
pause instruction via per-arch runtime modules, yielding only about once
per millisecond. Halide mutexes share the same spin strategy, so the
keep-awake count also extends spinning on contended mutexes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Shutdown no longer overwrites a handoff that holds a job the worker
  hasn't taken yet. That dropped the task and the worker's reference to
  the job, so its owner waited forever.
- Enqueuers acquire a worker's idle flag before reusing its handoff
  slot, and the worker clears the slot atomically.
- Access greedy and active_workers atomically where they're read
  without the lock, or while they can be changed without it.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Stickiness was an experiment toggle; the sticky assignment is now
the only mode.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- When an owned job's parent has failed, fail the job's siblings too.
  Failing only the owned job abandoned its unclaimed tasks, which could
  leave a sibling consumer waiting forever on a semaphore those tasks
  would have released.

- Remove the thread over-commit assertion in enqueue_work_already_locked.
  An inner job's tasks keep their reservation on the parent after another
  outer iteration finishes and the parent's active_workers drops, so a
  later enqueue can legitimately see a negative budget. The scheduling
  gate at task start already enforces min_threads. Main also hits this
  assertion, e.g. with an async producer inside two nested parallel
  loops (added to correctness_async).

- Workers that pass over a job only because too few unreserved threads
  are available now sleep with the semaphore-blocked workers, and
  returning a reservation wakes them. Previously they went idle and
  nothing woke them when the reservation came back, so the job could
  stall forever if its only other candidate was an owner that couldn't
  take it onto its stack.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Owners check every enclosing job for failure, not just the parent, so
  a nested job doesn't wait forever on semaphores a failed ancestor's
  abandoned tasks would have released.
- When a worker passes over or leaves behind runnable jobs on the stack
  and no blocked worker will be woken, it wakes an idle one, so a serial
  job blocked on a semaphore isn't stranded while every other thread is
  an owner waiting on a nested job.
- Factor the idle-worker wakeup out of enqueue_work_already_locked so
  those paths can use it.

Add generator_aot_thread_pool_fuzz, which drives the compiled runtime's
task system directly with random programs mirroring the Stmts
LowerParallelTasks emits, from several caller threads at once, checking
iteration counts, serial ordering, semaphore accounting, error
propagation, and hangs.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Brings in the front-end thread pool fuzzer, its lowering fixes, and its
tests. The pool fixes it made to the old thread pool are dropped in
favor of this branch's pool, which already handles those cases.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The default thread pool now performs as well as the app's statically
partitioned pool, so the app no longer needs its own.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Rename sems to semaphores, and read environment variables with getenv_s
on MSVC, which deprecates getenv.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@alexreinking
alexreinking added this pull request to stack #9737 December 1, 2026 00:55
@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 73.65%. Comparing base (80c4851) to head (39ceccb).

Additional details and impacted files
@@                      Coverage Diff                       @@
##           abadams/thread_pool_fuzzer    #9734      +/-   ##
==============================================================
+ Coverage                       73.53%   73.65%   +0.12%     
==============================================================
  Files                             266      266              
  Lines                           82881    82953      +72     
  Branches                        20535    20551      +16     
==============================================================
+ Hits                            60943    61099     +156     
+ Misses                          15455    15449       -6     
+ Partials                         6483     6405      -78     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

abadams and others added 2 commits December 1, 2026 08:59
The front-end thread pool fuzzer in test/fuzz replaces it.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The spin budgets assumed halide_spin_pause costs about 15ns, which holds
for x86 pause but not for the ARM yield instruction: on Apple silicon a
poll is about 0.3ns, so the nominal 30us budget was only about 0.6us.
Workers and the owning thread fell asleep almost immediately and paid
wake-up latency on every parallel loop, which made cheap parallel loops
slower than with the old thread pool.

spin_until now reads halide_current_time_ns at doubling poll counts
(and at least every 4096 polls) and stops after HALIDE_THREAD_POOL_SPIN_NS
(or HALIDE_THREAD_POOL_KEEP_AWAKE_MAX_NS while keep-awake is held). The
clock is started at thread pool initialization; until then, and on QuRT,
which links no clock module, polls are assumed to take 15ns as before.

This commit was written by GitHub Copilot on behalf of Andrew Adams.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@abadams
abadams force-pushed the abadams/sticky_threads branch from 664f7bf to 1d47801 Compare December 1, 2026 18:18
abadams and others added 3 commits December 1, 2026 12:06
spin_until no longer reads the clock when a spin starts. The first read is
after 1024 polls, and the time taken by those polls is estimated from later
reads. Reads then happen whenever the poll count doubles, up to every 65536
polls. This cuts clock reads by 10-20x on Linux, where halide_current_time_ns
is a syscall, and recovers 4-10% regressions in interpolate, lens_blur and
local_laplacian (auto schedules).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Restore threads_promised accounting so concurrent top-level callers
can't over-reserve the pool and deadlock (found by fuzz_thread_pool on
linux-32).

Make wait_on_address WEAK instead of ALWAYS_INLINE. When inlined into
worker_thread_idle, LLVM trunk SLP-vectorizes the parking control
construction into a <2 x ptr> GEP, which AArch64 ISel can't select
with +cpa (arm64e_x1).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Drop work::on_stack; an owner searches the job stack for its job instead.
- Drop the can_add_worker check: serial jobs are off the stack while
  being worked on.
- Shut down by handing idle workers look_for_work through
  wake_idle_workers_already_locked rather than a separate loop.
- run_simple_tasks takes an already-claimed task, claim_serial_tasks
  takes the end offset, and the bitmask is built with a single shift.
- Start the clock unconditionally on pool init; halide_start_clock is
  idempotent.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants