Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_gc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1658,6 +1658,25 @@ def test_indirect_calls_with_gc_disabled(self):
finally:
gc.enable()

def test_get_count_nonnegative(self):
xs = [[] for _ in range(1500)]
gc.collect()
del xs[:1000]
self.assertGreaterEqual(gc.get_count()[0], 0)

@gc_threshold(1000, 0, 0)
def test_get_count_does_not_prevent_collection(self):
junk = []
gc.collect()
detector = GC_Detector()
for _ in range(10000):
junk.append([])
gc.get_count()
if detector.gc_happened:
break
else:
self.fail("gc didn't happen after 10000 iterations")

# Ensure that setting *threshold0* to zero disables collection.
@gc_threshold(0)
def test_threshold_zero(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :func:`gc.get_count` on the free-threaded build resetting the thread-local
allocation counter that schedules automatic garbage collection. A thread that
called it while allocating could prevent cyclic garbage from ever being
collected.
11 changes: 7 additions & 4 deletions Modules/gcmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,12 @@ gc_get_count_impl(PyObject *module)
_PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
struct _gc_thread_state *gc = &tstate->gc;

// Flush the local allocation count to the global count
_Py_atomic_add_int(&gcstate->young.count, (int)gc->alloc_count);
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;
Comment thread
kumaraditya303 marked this conversation as resolved.
if (young < 0) {
young = 0;
}
#endif

#ifndef Py_GIL_DISABLED
Expand All @@ -233,7 +236,7 @@ gc_get_count_impl(PyObject *module)
gcstate->generations[2].count);
#else
return Py_BuildValue("(iii)",
_Py_atomic_load_int_relaxed(&gcstate->young.count),
young,
gcstate->old[0].count,
gcstate->old[1].count);
#endif
Expand Down
Loading