thread_pool: use acquire ordering in tasks_pending for ARM/POWER

tasks_pending() loads _tasks_completed then _tasks_enqueued and
returns the delta.  The bias-toward-zero property (safe for scaling
heuristics) depends on completed being observed no later than
enqueued.  With relaxed ordering on both loads, a weakly-ordered
CPU (ARM, POWER) can reorder the enqueued load before the completed
load, potentially observing a stale (lower) completed with a fresh
(higher) enqueued — over-reporting pending work.

Use acquire on the first load (_tasks_completed) so that subsequent
loads in program order cannot be reordered before it.  On x86 (TSO)
this compiles to the same instruction as relaxed, so there is zero
overhead on the primary target architecture.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Antonio S. Musumeci 2026-04-10 16:48:19 -04:00
parent 05413b86fd
commit 06a2ba2f35

View file

@ -1190,17 +1190,21 @@ ThreadPool::tasks_completed() const
return _tasks_completed.load(std::memory_order_relaxed);
}
// Approximate: the two counters are loaded non-atomically with
// relaxed ordering. Loading completed first biases the result
// toward zero (a completion between the two loads lowers the
// delta), which is safer for scaling heuristics than over-
// reporting pressure.
// Approximate: the two counters are loaded non-atomically.
// Loading completed first biases the result toward zero (a
// completion between the two loads lowers the delta), which is
// safer for scaling heuristics than over-reporting pressure.
//
// The first load uses acquire to prevent the CPU from reordering
// the enqueued load before the completed load. On x86 (TSO) this
// is free; on ARM/POWER it emits a barrier that preserves the
// intended load order so the bias-toward-zero property holds.
// Suitable for monitoring and heuristics, not for synchronization.
inline
std::uint64_t
ThreadPool::tasks_pending() const
{
auto c = _tasks_completed.load(std::memory_order_relaxed);
auto c = _tasks_completed.load(std::memory_order_acquire);
auto e = _tasks_enqueued.load(std::memory_order_relaxed);
return (e > c) ? (e - c) : 0;
}