Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-157377: Don't flush the thread-local allocation count in gc.get_count - #157381

Open
ngoldbaum wants to merge 2 commits into
python:mainfrom
ngoldbaum:fix-gc-get-count
Open

gh-157377: Don't flush the thread-local allocation count in gc.get_count#157381
ngoldbaum wants to merge 2 commits into
python:mainfrom
ngoldbaum:fix-gc-get-count

Conversation

@ngoldbaum

@ngoldbaum ngoldbaum commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

On the free-threaded build, gc.get_count() flushed the allocation counter into the global young count and reset it. Modifying the local count leads to pathological cases like in the linked issue. It could also flush negative local counts into the global count, which bypassed the clamp from gh-142048 and led to under-collection compared with not calling get_count().

With this change, get_count() returns the global count plus the local counter without modifying either. The reported value still includes the caller's buffered allocations, and scheduling behaves exactly as if get_count() had never been called.

Comment thread Modules/gcmodule.c
gc->alloc_count = 0;
// Don't flush: record_allocation() checks the threshold only when it fills.
int young = _Py_atomic_load_int_relaxed(&gcstate->young.count);
young += (int)gc->alloc_count;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think young needs to be clamped with if (young < 0) young = 0; otherwise negative values can be reported like:

xs = [[] for _ in range(600)]; gc.collect(); del xs[:400]
gc.get_count()  ->  (-173, 0, 0)     # with the PR applied

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense and is consistent with the clamping of the global count done in gh-142048. When that happened the behavior of this function from gh-112529 was not revisited.

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

Labels

awaiting core review needs backport to 3.14 bugs and security fixes needs backport to 3.15 pre-release feature fixes, bugs and security fixes topic-free-threading

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants