diff --git a/src/greenlet/TGreenletGlobals.cpp b/src/greenlet/TGreenletGlobals.cpp index a67797ad..b54a2e84 100644 --- a/src/greenlet/TGreenletGlobals.cpp +++ b/src/greenlet/TGreenletGlobals.cpp @@ -44,6 +44,10 @@ class GreenletGlobals const greenlet::refs::ImmortalString str_run; Mutex* const thread_states_to_destroy_lock; greenlet::cleanup_queue_t thread_states_to_destroy; + // Set when AddToCleanupQueue schedules PendingCallback_DestroyQueue and cleared + // by PendingCallback_DestroyQueue only when it observes the queue empty under + // thread_states_to_destroy_lock. + mutable bool cleanup_scheduled; GreenletGlobals() : event_switch("switch"), @@ -53,7 +57,8 @@ class GreenletGlobals empty_tuple(Require(PyTuple_New(0))), empty_dict(Require(PyDict_New())), str_run("run"), - thread_states_to_destroy_lock(new Mutex()) + thread_states_to_destroy_lock(new Mutex()), + cleanup_scheduled(false) {} ~GreenletGlobals() diff --git a/src/greenlet/TThreadStateDestroy.cpp b/src/greenlet/TThreadStateDestroy.cpp index 5562a736..fede9d3d 100644 --- a/src/greenlet/TThreadStateDestroy.cpp +++ b/src/greenlet/TThreadStateDestroy.cpp @@ -102,19 +102,13 @@ struct ThreadState_DestroyNoGIL LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); mod_globs->queue_to_destroy(state); - if (mod_globs->thread_states_to_destroy.size() == 1) { - // We added the first item to the queue. We need to schedule - // the cleanup. - - // A size greater than 1 means that we have already added the pending call, - // and in fact, it may be executing now. - // If it is executing, our lock makes sure that it will see the item we just added - // to the queue on its next iteration (after we release the lock) - // - // A size of 1 means there is no pending call, OR the pending call is - // currently executing, has dropped the lock, and is deleting the last item - // from the queue; its next iteration will go ahead and delete the item we just added. - // And the pending call we schedule here will have no work to do. + if (!mod_globs->cleanup_scheduled) { + // Schedule at most one pending cleanup callback until the drain + // loop empties the queue. Scheduling another Py_AddPendingCall + // while PendingCallback_DestroyQueue is already running inside + // Py_MakePendingCalls() (e.g., while DestroyOne runs Python + // weakref callbacks) leaves the eval breaker set on CPython 3.11 + // and livelocks under sys.settrace(). int result = AddPendingCall( PendingCallback_DestroyQueue, nullptr); @@ -123,6 +117,8 @@ struct ThreadState_DestroyNoGIL fprintf(stderr, "greenlet: WARNING: failed in call to Py_AddPendingCall; " "expect a memory leak.\n"); + } else { + mod_globs->cleanup_scheduled = true; } } } @@ -138,6 +134,7 @@ struct ThreadState_DestroyNoGIL { LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); if (mod_globs->thread_states_to_destroy.empty()) { + mod_globs->cleanup_scheduled = false; break; } to_destroy = mod_globs->take_next_to_destroy(); diff --git a/src/greenlet/tests/test_tracing.py b/src/greenlet/tests/test_tracing.py index c54a910a..f2cb43ae 100644 --- a/src/greenlet/tests/test_tracing.py +++ b/src/greenlet/tests/test_tracing.py @@ -1,5 +1,7 @@ +import subprocess import sys import sysconfig +import textwrap import greenlet import unittest @@ -293,6 +295,68 @@ def g2_run(): ('c_call', '__exit__'), ]) + def test_cleanup_during_pending_call_with_trace_no_livelock(self): + # Regression test for issue #535: a second thread exiting while + # PendingCallback_DestroyQueue is destroying a main greenlet must not + # schedule a redundant pending call that livelocks sys.settrace(). + script = textwrap.dedent("""\ + import sys + import threading + import time + import weakref + import greenlet + from greenlet._greenlet import get_pending_cleanup_count + + b_ready = threading.Event() + release_b = threading.Event() + state = {} + + def _in_cleanup(_ref): + release_b.set() + deadline = time.monotonic() + 10 + while get_pending_cleanup_count() == 0 and time.monotonic() < deadline: + time.sleep(0.001) + state["b_queued"] = get_pending_cleanup_count() > 0 + (lambda: None)() + + def _a(): + state["ref"] = weakref.ref(greenlet.getcurrent(), _in_cleanup) + + def _b(): + greenlet.getcurrent() + b_ready.set() + release_b.wait() + + sys.settrace(lambda *args: None) + b = threading.Thread(target=_b) + b.start() + b_ready.wait() + a = threading.Thread(target=_a) + a.start() + a.join() + for _ in range(5000): + time.sleep(0.001) + if "b_queued" in state and get_pending_cleanup_count() == 0: + break + b.join() + assert state.get("b_queued") is True, state + assert get_pending_cleanup_count() == 0 + print("GREEN", state["b_queued"]) + """) + result = subprocess.run( + [sys.executable, '-c', script], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + self.assertEqual( + result.returncode, + 0, + "stdout=%r stderr=%r" % (result.stdout, result.stderr), + ) + self.assertIn("GREEN True", result.stdout) + if __name__ == '__main__': unittest.main()