Fix set_threads over-shrink when prior removals are still pending

set_threads computed its delta from _threads.size(), which does not
reflect _remove_count signals already in flight.  If called twice
before workers drained the first batch of removals, the second call
would see the original thread count and issue a full set of redundant
removal signals, potentially shrinking the pool well below the
requested target.

Fix: compute the effective thread count as _threads.size() minus
pending _remove_count, and use that as the baseline for the grow/shrink
delta.  This makes set_threads idempotent regardless of drain timing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Antonio S. Musumeci 2026-04-10 12:59:16 -04:00
parent 62d905bb29
commit a90e13a19d

View file

@ -852,22 +852,29 @@ ThreadPool::set_threads(const std::size_t count_)
}
std::size_t current;
std::size_t pending;
{
mutex_lockguard(_threads_mutex);
current = _threads.size();
}
// Account for removal signals already in flight so we don't
// over-shrink when set_threads is called before prior removals
// have drained.
pending = _remove_count.load(std::memory_order_relaxed);
std::size_t effective = (current > pending) ? (current - pending) : 0;
int rv = 0;
for(std::size_t i = current; i < count; ++i)
for(std::size_t i = effective; i < count; ++i)
{
rv = _add_thread_scaling_locked({});
if(rv != 0)
return rv;
}
for(std::size_t i = count; i < current; ++i)
for(std::size_t i = count; i < effective; ++i)
{
rv = _remove_thread_scaling_locked();
if(rv != 0)