Title: Thread.start() can hang indefinitely if the new thread fails (MemoryError) during its initialization · Issue #140746 · python/cpython · GitHub
Open Graph Title: Thread.start() can hang indefinitely if the new thread fails (MemoryError) during its initialization · Issue #140746 · python/cpython
X Title: Thread.start() can hang indefinitely if the new thread fails (MemoryError) during its initialization · Issue #140746 · python/cpython
Description: Bug report Bug description: There is a race condition in the threading module where a parent thread calling Thread.start() can wait forever if the newly created thread crashes with a MemoryError during its internal bootstrap process. Cas...
Open Graph Description: Bug report Bug description: There is a race condition in the threading module where a parent thread calling Thread.start() can wait forever if the newly created thread crashes with a MemoryError du...
X Description: Bug report Bug description: There is a race condition in the threading module where a parent thread calling Thread.start() can wait forever if the newly created thread crashes with a MemoryError du...
Opengraph URL: https://github.com/python/cpython/issues/140746
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Thread.start() can hang indefinitely if the new thread fails (MemoryError) during its initialization","articleBody":"# Bug report\n\n### Bug description:\n\nThere is a race condition in the threading module where a parent thread calling `Thread.start()` can wait forever if the newly created thread crashes with a `MemoryError` during its internal bootstrap process.\n\n### Case Explanation\n\nIn case we have a \"Serving Thread\" that creates threads on demand (e.g., for each HTTP request):\n\n- When this Serving Thread calls `Thread.start()`, the OS-level thread (`pthread_create()`[^1] - Linux) is successfully created. The parent thread then waits for the new thread to signal that it has started correctly by calling `self._started.wait()`[^2].\n- The new thread starts, but before it can signal the parent thread (Serving Thread) that it is alive with `self._started.set()`[^3] it encounters a `MemoryError`.\n- This `MemoryError` can occur at the C level during the `PyObject_Call` to the `_bootstrap` method or inside the `_bootstrap_inner` method before `_started.set()` is reached, often due to memory pressure from other threads (or a heap limit being reached).\n- This exception is caught by the C-level entry point `thread_run()`, which calls `_PyErr_WriteUnraisableMsg`[^4] and prints \"Exception ignored in thread started by: ...\"\n\nThe new thread then exits without ever signaling the `_started` event, and the parent thread waits indefinitely on the `_started.wait()`.\nThis also leaves the `threading` module in an inconsistent state, as the \"zombie\" thread object may not be correctly cleaned up from the `_limbo` dict.\n\n### How to Reproduce\n\nThis has been observed in high-concurrency server applications under heavy, sustained load, where heap memory can be rapidly consumed and exhausted by concurrent threads [^5].\nThis is a race condition that is difficult to reproduce reliably, as it requires triggering a `MemoryError` at a specific moment.\n\nI found a (deterministic?) way to reproduce the issue by restricting the heap memory until it reaches a threshold where we can start a new thread, but this new thread won't get enough memory for its initialization. \n\nOn some machines (and depending of Python versions), it is sometimes necessary to tweak `HARD_LIMIT_START` / `LIMIT_REDUCTION` (I reproduced it on Ubuntu based machine with Python 3.11/3.12/3.13/3.14)\n\n```python\nimport resource\nimport threading\nimport gc\n\ndef handler():\n pass\n\ndef serving():\n # These should be tweak (depending of Python version + system)\n HARD_LIMIT_START = 30_000_000\n LIMIT_REDUCTION = 5_000\n\n for _ in range(500_000):\n gc.collect(2) # Force getting back memory: seems to increase the determinism of the script\n\n # Limit the heap size available for this process\n resource.setrlimit(resource.RLIMIT_DATA, (HARD_LIMIT_START, HARD_LIMIT_START * 2))\n try:\n handler_thread = threading.Thread(target=handler)\n print(f'Start Thread: {handler_thread} - Heap size limit : {HARD_LIMIT_START}')\n handler_thread.start()\n handler_thread.join()\n HARD_LIMIT_START -= LIMIT_REDUCTION\n except RuntimeError as r: # If Python refused to launch a new Thread\n print(f'RuntimeError: {r} - Cannot start the thread at all => error not detected.')\n return\n\nserving_thread = threading.Thread(target=serving)\nserving_thread.start()\nserving_thread.join()\n```\n\n### Expected Behavior\n\nI am not sure if this is an \"accepted\" limitation of (CPython) Thread or not. IMO, `Thread.start()` shouldn't hang indefinitely if the low-level thread is dead.\n\nI didn't take the time to try to fix it yet (if possible). I would prefer to get your opinions on this first.\n\n[^1]: https://github.com/python/cpython/blob/25243b1461e524560639ebe54bab9b689b6cc31e/Python/thread_pthread.h#L284\n[^2]: https://github.com/python/cpython/blob/f463d05a0979aada4fadcd43ff721b1ff081d2aa/Lib/threading.py#L999\n[^3]: https://github.com/python/cpython/blob/f463d05a0979aada4fadcd43ff721b1ff081d2aa/Lib/threading.py#L1064\n[^4]: https://github.com/python/cpython/blob/89a79fc919419bfe817da13bc2a4437908d7fc07/Modules/_threadmodule.c#L1122\n[^5]: https://github.com/odoo/odoo/blob/350f7b10d4048b84d4a5f9e5aca9a88b8b971801/odoo/service/server.py#L273\n\n### CPython versions tested on:\n\n3.12, 3.13, 3.14\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-140799\n* gh-144750\n* gh-153776\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/ryv-odoo","@type":"Person","name":"ryv-odoo"},"datePublished":"2025-10-29T10:23:09Z","url":"https://github.com/python/cpython/issues/140746"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:84528e43-1725-81e0-cd7d-505bd78f94a8 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B4B6:27E5CD:4550683:5874E21:6B0231B7 |
| html-safe-nonce | 559b7a2b487a220dbb67b42318896595cd2324f3d491b796f9178176ed4c9d0f |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCNEI2OjI3RTVDRDo0NTUwNjgzOjU4NzRFMjE6NkIwMjMxQjciLCJ2aXNpdG9yX2lkIjoiMjI0MTM4ODMxMjI0Mzg3NjI3OSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 8a1a284fc178d17dff7a898863124182ef1e6d2f7dc4adcd569405990147405e |
| hovercard-subject-tag | issue:3565280910 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/140746/issue_layout |
| twitter:image | https://opengraph.githubassets.com/f1e56870a46853033c92e3c0675cb294c67c785a4cd95d24365d518099e70405/python/cpython/issues/140746 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/f1e56870a46853033c92e3c0675cb294c67c785a4cd95d24365d518099e70405/python/cpython/issues/140746 |
| og:image:alt | Bug report Bug description: There is a race condition in the threading module where a parent thread calling Thread.start() can wait forever if the newly created thread crashes with a MemoryError du... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | ryv-odoo |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width