Skip to content

Commit 0f7e1b0

Browse files
authored
PYTHON-4147: Silence noisy thread.start() RuntimeError at shutdown (#1486)
1 parent da2bf9d commit 0f7e1b0

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

doc/changelog.rst

+3
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ PyMongo 4.7 brings a number of improvements including:
2929

3030
.. _orjson: https://github.com/ijl/orjson
3131

32+
- Fixed a bug appearing in Python 3.12 where "RuntimeError: can't create new thread at interpreter shutdown"
33+
could be written to stderr when a MongoClient's thread starts as the python interpreter is shutting down.
34+
3235
Changes in Version 4.6.1
3336
------------------------
3437

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
@@ -91,7 +92,15 @@ def open(self) -> None:
9192
thread.daemon = True
9293
self._thread = weakref.proxy(thread)
9394
_register_executor(self)
94-
thread.start()
95+
# Mitigation to RuntimeError firing when thread starts on shutdown
96+
# https://github.com/python/cpython/issues/114570
97+
try:
98+
thread.start()
99+
except RuntimeError as e:
100+
if "interpreter shutdown" in str(e) or sys.is_finalizing():
101+
self._thread = None
102+
return
103+
raise
95104

96105
def close(self, dummy: Any = None) -> None:
97106
"""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+
" ".join(command), shell=True, 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)