Skip to content

Commit d8ce02d

Browse files
committed
Fix race during event spinning.
1 parent 6c62b40 commit d8ce02d

1 file changed

Lines changed: 17 additions & 14 deletions

File tree

Python/pylifecycle.c

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2316,22 +2316,24 @@ make_pre_finalization_calls(PyThreadState *tstate, int subinterpreters)
23162316
* atomic check is made below, when we hold the finalization guard lock.
23172317
* Again, this is purely an optimization to avoid overloading the CPU.
23182318
*/
2319-
if (_Py_atomic_load_ssize_relaxed(&interp->finalization_guards.countdown) > 0) {
2320-
for (;;) {
2321-
PyTime_t wait_ns = 1000 * 1000; // 1ms
2322-
if (PyEvent_WaitTimed(&interp->finalization_guards.done, wait_ns, /*detach=*/1)) {
2323-
break;
2324-
}
2319+
for (;;) {
2320+
if (_Py_atomic_load_ssize_relaxed(&interp->finalization_guards.countdown) == 0) {
2321+
break;
2322+
}
23252323

2326-
// For debugging purposes, we emit a fatal error if someone
2327-
// CTRL^C'ed the process.
2328-
if (PyErr_CheckSignals()) {
2329-
int fatal = PyErr_ExceptionMatches(PyExc_KeyboardInterrupt);
2330-
PyErr_FormatUnraisable("Exception ignored while waiting on finalization guards");
2324+
PyTime_t wait_ns = 1000 * 1000; // 1ms
2325+
if (PyEvent_WaitTimed(&interp->finalization_guards.done, wait_ns, /*detach=*/1)) {
2326+
break;
2327+
}
23312328

2332-
if (fatal) {
2333-
Py_FatalError("Interrupted while waiting on finalization guard");
2334-
}
2329+
// For debugging purposes, we emit a fatal error if someone
2330+
// CTRL^C'ed the process.
2331+
if (PyErr_CheckSignals()) {
2332+
int fatal = PyErr_ExceptionMatches(PyExc_KeyboardInterrupt);
2333+
PyErr_FormatUnraisable("Exception ignored while waiting on finalization guards");
2334+
2335+
if (fatal) {
2336+
Py_FatalError("Interrupted while waiting on finalization guard");
23352337
}
23362338
}
23372339
}
@@ -2366,6 +2368,7 @@ make_pre_finalization_calls(PyThreadState *tstate, int subinterpreters)
23662368
_PyThreadState_Attach(tstate);
23672369
}
23682370
assert(PyMutex_IsLocked(&interp->ceval.pending.mutex));
2371+
assert(_Py_atomic_load_ssize(&interp->finalization_guards.countdown) == 0);
23692372
ASSERT_WORLD_STOPPED(interp);
23702373
}
23712374

0 commit comments

Comments
 (0)