Skip to content

Commit a9edb7b

Browse files
committed
reset allocation counts in gc thread-local buffers
1 parent fa9519f commit a9edb7b

2 files changed

Lines changed: 12 additions & 5 deletions

File tree

Python/gc_free_threading.c

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2207,11 +2207,10 @@ record_deallocation(PyThreadState *tstate)
22072207
{
22082208
struct _gc_thread_state *gc = &((_PyThreadStateImpl *)tstate)->gc;
22092209

2210-
gc->alloc_count--;
2211-
if (gc->alloc_count <= -LOCAL_ALLOC_COUNT_THRESHOLD) {
2212-
GCState *gcstate = &tstate->interp->gc;
2213-
_Py_atomic_add_int(&gcstate->young.count, (int)gc->alloc_count);
2214-
gc->alloc_count = 0;
2210+
// Only decrement if positive, matching gc.c behavior which prevents
2211+
// negative counts (see PyObject_GC_Del in gc.c).
2212+
if (gc->alloc_count > 0) {
2213+
gc->alloc_count--;
22152214
}
22162215
}
22172216

Python/pystate.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1810,6 +1810,14 @@ tstate_delete_common(PyThreadState *tstate, int release_gil)
18101810
assert(tstate_impl->refcounts.values == NULL);
18111811
#endif
18121812

1813+
#ifdef Py_GIL_DISABLED
1814+
// Flush the thread's local GC allocation count to the global count
1815+
// before the thread state is deleted, otherwise the count is lost.
1816+
_Py_atomic_add_int(&tstate->interp->gc.young.count,
1817+
(int)((_PyThreadStateImpl *)tstate)->gc.alloc_count);
1818+
((_PyThreadStateImpl *)tstate)->gc.alloc_count = 0;
1819+
#endif
1820+
18131821
#if _Py_TIER2
18141822
_PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
18151823
if (_tstate->jit_tracer_state.code_buffer != NULL) {

0 commit comments

Comments
 (0)