8000 Fix thread leak in Python 3.7 #340 (#356) · sxlstevengit/client_python@5aa256d · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 5aa256d

Browse files
sbrandtbbrian-brazil
authored andcommitted
Fix thread leak in Python 3.7 prometheus#340 (prometheus#356)
* Fix thread leak in Python 3.7 prometheus#340 The leak is caused by the fact that in Python 3.7, the default behavior of the `ThreadingMixin` is to use no daemon threads, but to request to block on threads on close. Because of that, it collects references to all created threads, creating the "leak": https://github.com/python/cpython/blob/v3.7.0/Lib/socketserver.py#L661 * Python 3.7: `block_on_close` is `True`: https://github.com/python/cpython/blob/v3.7.0/Lib/socketserver.py#L635 * Python 3.6: `_block_on_close` is `False`: https://github.com/python/cpython/blob/v3.6.7/Lib/socketserver.py#L639 * Python 2.7: There is no `block_on_close`, thus no logic for collecting references: https://github.com/python/cpython/blob/v2.7.15/Lib/SocketServer.py#L582 Fix by setting `daemon_threads` to `True`, which in our case should be a reasonable setting for all Python versions. Also, the new in Python 3.7 `ThreadingHTTPServer` stdlib class also sets it by default: https://github.com/python/cpython/blob/v3.7.0/Lib/http/server.py#L144 Signed-off-by: Sebastian Brandt <sebastian.brandt@friday.de>
1 parent d7c70f2 commit 5aa256d

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

prometheus_client/exposition.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,12 @@ def factory(cls, registry):
173173

174174
class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
175175
"""Thread per request HTTP server."""
176+
# Make worker threads "fire and forget". Beginning with Python 3.7 this
177+
# prevents a memory leak because ``ThreadingMixIn`` starts to gather all
178+
# non-daemon threads in a list in order to join on them at server close.
179+
# Enabling daemon threads virtually makes ``_ThreadingSimpleServer`` the
180+
# same as Python 3.7's ``ThreadingHTTPServer``.
181+
daemon_threads = True
176182

177183

178184
def start_http_server(port, addr='', registry=REGISTRY):

0 commit comments

Comments
 (0)
0