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
16 changes: 16 additions & 0 deletions Lib/test/test_free_threading/test_races.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,22 @@ def set_recursion_limit():

do_race(something_recursive, set_recursion_limit)

def test_racing_intern_queued_for_merge(self):
# gh-152276: an object may become immortal while it is queued for
# its owning thread to merge its reference count.
# The same strings are used on every run, so that reruns do not
# create new immortal strings.
for i in range(10):
strings = [f"test_racing_intern_queued_for_merge_{i}_{j}"
for j in range(1000)]
shared = list(strings)
# Dropping the references from another thread queues the strings
# to be merged by this thread, which is busy interning them.
thread = threading.Thread(target=shared.clear)
thread.start()
list(map(sys.intern, strings))
thread.join()


@threading_helper.requires_working_threading()
class TestWarningsRaces(TestBase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
For the :term:`free-threaded build`, avoid an assertion failure when an object
becomes immortal while queued for biased reference counting (BRC) merging.
7 changes: 6 additions & 1 deletion Objects/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,12 @@ _Py_MergeZeroLocalRefcount(PyObject *op)
Py_ssize_t
_Py_ExplicitMergeRefcount(PyObject *op, Py_ssize_t extra)
{
assert(!_Py_IsImmortal(op));
if (_Py_IsImmortal(op)) {
// The object may have become immortal after it was queued to be
// merged (for example, by sys.intern()). There is nothing to merge
// and the reference total no longer includes the object.
return _Py_IMMORTAL_INITIAL_REFCNT;
}

#ifdef Py_REF_DEBUG
_Py_AddRefTotal(_PyThreadState_GET(), extra);
Expand Down
Loading