fix tasks_pending() load ordering to bias toward zero as intended

The previous ordering loaded completed before enqueued, which meant a
completion between the two loads would be missed (stale lower c),
inflating the delta and over-reporting pending tasks. This is the
opposite of what the comment claimed. Swapping to load enqueued first
means a completion between the two loads yields a higher c, shrinking
the delta — biasing toward zero, which is the safe direction for
scaling heuristics.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Antonio S. Musumeci 2026-04-10 22:12:02 -04:00
parent 911d31c04e
commit 12a3a689ed

View file

@ -1281,15 +1281,16 @@ ThreadPool::tasks_completed() const
}
// 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.
// Loading enqueued first biases the result toward zero (a
// completion between the two loads increases c beyond the
// snapshot of e, shrinking the delta), which is safer for
// scaling heuristics than over-reporting pressure.
// 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 e = _tasks_enqueued.load(std::memory_order_relaxed);
auto c = _tasks_completed.load(std::memory_order_relaxed);
return (e > c) ? (e - c) : 0;
}