Skip to content

Commit d29b2b7

Browse files
blink1073Jibola
andauthored
PYTHON-4147 [v4.6]: Silence noisy thread.start() RuntimeError at shutdown (#1532)
Co-authored-by: Jib <[email protected]>
1 parent 0477b9b commit d29b2b7

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

pymongo/periodic_executor.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
from __future__ import annotations
1818

19+
import sys
1920
import threading
2021
import time
2122
import weakref
@@ -92,7 +93,15 @@ def open(self) -> None:
9293
thread.daemon = True
9394
self._thread = weakref.proxy(thread)
9495
_register_executor(self)
95-
thread.start()
96+
# Mitigation to RuntimeError firing when thread starts on shutdown
97+
# https://github.com/python/cpython/issues/114570
98+
try:
99+
thread.start()
100+
except RuntimeError as e:
101+
if "interpreter shutdown" in str(e) or sys.is_finalizing():
102+
self._thread = None
103+
return
104+
raise
96105

97106
def close(self, dummy: Any = None) -> None:
98107
"""Stop. To restart, call open().

test/test_monitor.py

+12
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from __future__ import annotations
1717

1818
import gc
19+
import subprocess
1920
import sys
2021
from functools import partial
2122

@@ -79,6 +80,17 @@ def test_cleanup_executors_on_client_close(self):
7980
for executor in executors:
8081
wait_until(lambda: executor._stopped, f"closed executor: {executor._name}", timeout=5)
8182

83+
def test_no_thread_start_runtime_err_on_shutdown(self):
84+
"""Test we silence noisy runtime errors fired when the MongoClient spawns a new thread
85+
on process shutdown."""
86+
command = [sys.executable, "-c", "from pymongo import MongoClient; c = MongoClient()"]
87+
completed_process: subprocess.CompletedProcess = subprocess.run(
88+
command, capture_output=True
89+
)
90+
91+
self.assertFalse(completed_process.stderr)
92+
self.assertFalse(completed_process.stdout)
93+
8294

8395
if __name__ == "__main__":
8496
unittest.main()

0 commit comments

Comments
 (0)