Skip to content

Commit 32d59ce

Browse files
[3.15] gh-160682: Track running function objects in free-threaded GC …(GH-160707) (#162005)
[3.15] gh-160682: Track running function objects in free-threaded GC (GH-160707) (cherry picked from commit b3683c0) Co-authored-by: Vankudothu Adhi Naik <22je1052@iitism.ac.in>
1 parent 6a9fa39 commit 32d59ce

3 files changed

Lines changed: 20 additions & 0 deletions

File tree

‎Lib/test/test_free_threading/test_gc.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,19 @@ def mutate():
118118
b.wait()
119119
time.sleep(0.2)
120120

121+
def test_running_method_not_collected(self):
122+
class C:
123+
def m(self):
124+
wr = weakref.ref(C.__dict__["m"])
125+
del C.m
126+
gc.collect()
127+
return wr() is not None
128+
129+
def run(self):
130+
return self.m()
131+
132+
self.assertTrue(C().run())
133+
121134
def test_merge_brc_queue_of_detached_thread(self):
122135
# GH-157838: objects queued for merging by a thread that is detached
123136
# (blocked in a lock acquire, sleep, etc.) are merged and freed on its
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a bug in the :term:`free-threaded build` where garbage collection could
2+
prematurely collect the function object of a running method.

‎Python/gc_free_threading.c‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,7 @@ gc_visit_thread_stacks(PyInterpreterState *interp, struct collection_state *stat
469469
continue;
470470
}
471471

472+
gc_visit_stackref(f->f_funcobj);
472473
gc_visit_stackref(f->f_executable);
473474
while (top != f->localsplus) {
474475
--top;
@@ -865,6 +866,10 @@ gc_visit_thread_stacks_mark_alive(PyInterpreterState *interp, gc_mark_args_t *ar
865866
}
866867

867868
_PyStackRef *top = f->stackpointer;
869+
if (gc_visit_stackref_mark_alive(args, f->f_funcobj) < 0) {
870+
err = -1;
871+
goto exit;
872+
}
868873
if (gc_visit_stackref_mark_alive(args, f->f_executable) < 0) {
869874
err = -1;
870875
goto exit;

0 commit comments

Comments
 (0)