René's URL Explorer Experiment


Title: gh-154937: Fix `_thread._shutdown()` racing with `_thread.start_joinable_thread` on `ThreadHandle.ident` by LindaSummer · Pull Request #155085 · python/cpython · GitHub

Open Graph Title: gh-154937: Fix `_thread._shutdown()` racing with `_thread.start_joinable_thread` on `ThreadHandle.ident` by LindaSummer · Pull Request #155085 · python/cpython

X Title: gh-154937: Fix `_thread._shutdown()` racing with `_thread.start_joinable_thread` on `ThreadHandle.ident` by LindaSummer · Pull Request #155085 · python/cpython

Description: Issue Close #154937 Proposed Changes The ThreadHandle.ident should be guarded by ThreadHandle.mutex as the below comment. cpython/Modules/_threadmodule.c Lines 132 to 136 in 083e038 // The `ident`, `os_handle`, `has_os_handle`, and `state` fields are // protected by `mutex`. PyThread_ident_t ident; PyThread_handle_t os_handle; int has_os_handle; Root Cause The thread.Thread will invoke _start_joinable_thread with the same flag as the invoke thread. The main thread is a non-daemon thread. cpython/Lib/threading.py Lines 1111 to 1147 in 083e038 def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError("thread.__init__() not called") if self._started.is_set(): raise RuntimeError("threads can only be started once") with _active_limbo_lock: _limbo[self] = self if self._context is None: # No context provided if _sys.flags.thread_inherit_context: # start with a copy of the context of the caller self._context = _contextvars.copy_context() else: # start with an empty context self._context = _contextvars.Context() try: # Start joinable thread _start_joinable_thread(self._bootstrap, handle=self._os_thread_handle, daemon=self.daemon) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait() # Will set ident and native_id cpython/Lib/threading.py Lines 1527 to 1537 in 083e038 class _MainThread(Thread): def __init__(self): Thread.__init__(self, name="MainThread", daemon=False) self._started.set() self._ident = _get_main_thread_ident() self._os_thread_handle = _make_thread_handle(self._ident) if _HAVE_THREAD_NATIVE_ID: self._set_native_id() with _active_limbo_lock: _active[self._ident] = self In _start_joinable_thread=>do_start_new_thread, the non-daemon thread will add to the shutdown_handles. cpython/Modules/_threadmodule.c Lines 1912 to 1917 in 083e038 if (!daemon) { // Add the handle before starting the thread to avoid adding a handle // to a thread that has already finished (i.e. if the thread finishes // before the call to `ThreadHandle_start()` below returns). add_to_shutdown_handles(state, handle); } After being added to shutdown_handlers, do_start_new_thread will invoke ThreadHandle_start, where the racing happened. cpython/Modules/_threadmodule.c Lines 483 to 490 in 083e038 // Mark the handle running PyMutex_Lock(&self->mutex); assert(self->state == THREAD_HANDLE_STARTING); self->ident = ident; self->has_os_handle = 1; self->os_handle = os_handle; self->state = THREAD_HANDLE_RUNNING; PyMutex_Unlock(&self->mutex); At the same time, _shutdown will read the ident for shutting down without a lock with the ThreadHandle.mutex. cpython/Modules/_threadmodule.c Lines 2403 to 2422 in 083e038 thread_shutdown(PyObject *self, PyObject *args) { PyThread_ident_t ident = PyThread_get_thread_ident_ex(); thread_module_state *state = get_thread_state(self); for (;;) { ThreadHandle *handle = NULL; // Find a thread that's not yet finished. HEAD_LOCK(&_PyRuntime); struct llist_node *node; llist_for_each_safe(node, &state->shutdown_handles) { ThreadHandle *cur = llist_data(node, ThreadHandle, shutdown_node); if (cur->ident != ident) { ThreadHandle_incref(cur); handle = cur; break; } } HEAD_UNLOCK(&_PyRuntime); Comment Referring to the above root cause analytics, I find the original test case may not be precise. The original case in #154937 uses _thread.start_new_thread alongside threading.Thread. The race was caused by threading.Thread not _thread.start_new_thread. def chain2_thread(): for _ in range(12000): try: _thread.start_new_thread(lambda: None, ()) except Exception: pass time.sleep(0.0001) ... threads += [Thread(target=chain2_thread) for _ in range(N_C2)] So, I changed the original case to below with daemon=True, and the racing doesn't happen. import _thread import time from threading import Thread def chain1_thread(): for _ in range(12000): try: _thread._shutdown() except Exception: pass def chain2_thread(): for _ in range(12000): try: _thread.start_new_thread(lambda: None, ()) except Exception: pass time.sleep(0.0001) N_C1 = 1 N_C2 = 8 threads = [Thread(target=chain1_thread, daemon=True) for _ in range(N_C1)] threads += [Thread(target=chain2_thread, daemon=True) for _ in range(N_C2)] for t in threads: t.start() for t in threads: t.join() I created another case that aligns with the PR's unit test, and the problem is reproduced again. import _thread from threading import Barrier ITERATIONS = 1_000 phase = Barrier(2) def shutdown_worker(): phase.wait() for _ in range(ITERATIONS): try: _thread._shutdown() except RuntimeError: pass def startup_worker(): phase.wait() for _ in range(ITERATIONS): handle = _thread.start_joinable_thread( lambda: None, daemon=False, ) handle.join() startup_worker = _thread.start_joinable_thread( startup_worker, daemon=True, ) shutdown_worker = _thread.start_joinable_thread( shutdown_worker, daemon=True, ) shutdown_worker.join() startup_worker.join() Here is the TSAN report. WARNING: ThreadSanitizer: data race (pid=2708706) Read of size 8 at 0x7fca36010070 by thread T2: #0 thread_shutdown /home/someuser/projects/cpython/cpython-upstream-main/./Modules/_threadmodule.c:2416:22 (python3.16+0x653ba9) #1 cfunction_vectorcall_NOARGS /home/someuser/projects/cpython/cpython-upstream-main/Objects/methodobject.c:508:24 (python3.16+0x2ddf41) #2 _PyObject_VectorcallTstate /home/someuser/projects/cpython/cpython-upstream-main/./Include/internal/pycore_call.h:144:11 (python3.16+0x2240fc) #3 PyObject_Vectorcall /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:327:12 (python3.16+0x2240fc) #4 _Py_VectorCall_StackRefSteal /home/someuser/projects/cpython/cpython-upstream-main/Python/ceval.c:726:11 (python3.16+0x457e76) #5 _PyEval_EvalFrameDefault /home/someuser/projects/cpython/cpython-upstream-main/Python/generated_cases.c.h:4559:35 (python3.16+0x465a0c) #6 _PyEval_EvalFrame /home/someuser/projects/cpython/cpython-upstream-main/./Include/internal/pycore_ceval.h:122:16 (python3.16+0x457987) #7 _PyEval_Vector /home/someuser/projects/cpython/cpython-upstream-main/Python/ceval.c:2172:12 (python3.16+0x457987) #8 _PyFunction_Vectorcall /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c (python3.16+0x2247c7) #9 _PyVectorcall_Call /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:273:16 (python3.16+0x224416) #10 _PyObject_Call /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:348:16 (python3.16+0x224416) #11 PyObject_Call /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:373:12 (python3.16+0x22448b) #12 thread_run /home/someuser/projects/cpython/cpython-upstream-main/./Modules/_threadmodule.c:388:21 (python3.16+0x654aec) #13 pythread_wrapper /home/someuser/projects/cpython/cpython-upstream-main/Python/thread_pthread.h:234:5 (python3.16+0x574def) Previous write of size 8 at 0x7fca36010070 by thread T1: #0 ThreadHandle_start /home/someuser/projects/cpython/cpython-upstream-main/./Modules/_threadmodule.c:486:17 (python3.16+0x654966) #1 do_start_new_thread /home/someuser/projects/cpython/cpython-upstream-main/./Modules/_threadmodule.c:1919:9 (python3.16+0x6542ef) #2 thread_PyThread_start_joinable_thread /home/someuser/projects/cpython/cpython-upstream-main/./Modules/_threadmodule.c:2042:14 (python3.16+0x653268) #3 cfunction_call /home/someuser/projects/cpython/cpython-upstream-main/Objects/methodobject.c:564:18 (python3.16+0x2de9c5) #4 _PyObject_MakeTpCall /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:242:18 (python3.16+0x2232b3) #5 _PyObject_VectorcallTstate /home/someuser/projects/cpython/cpython-upstream-main/./Include/internal/pycore_call.h:142:16 (python3.16+0x2241c4) #6 PyObject_Vectorcall /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:327:12 (python3.16+0x2241c4) #7 _Py_VectorCallInstrumentation_StackRefSteal /home/someuser/projects/cpython/cpython-upstream-main/Python/ceval.c:768:11 (python3.16+0x4586f4) #8 _PyEval_EvalFrameDefault /home/someuser/projects/cpython/cpython-upstream-main/Python/generated_cases.c.h:3474:35 (python3.16+0x463029) #9 _PyEval_EvalFrame /home/someuser/projects/cpython/cpython-upstream-main/./Include/internal/pycore_ceval.h:122:16 (python3.16+0x457987) #10 _PyEval_Vector /home/someuser/projects/cpython/cpython-upstream-main/Python/ceval.c:2172:12 (python3.16+0x457987) #11 _PyFunction_Vectorcall /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c (python3.16+0x2247c7) #12 _PyVectorcall_Call /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:273:16 (python3.16+0x224416) #13 _PyObject_Call /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:348:16 (python3.16+0x224416) #14 PyObject_Call /home/someuser/projects/cpython/cpython-upstream-main/Objects/call.c:373:12 (python3.16+0x22448b) #15 thread_run /home/someuser/projects/cpython/cpython-upstream-main/./Modules/_threadmodule.c:388:21 (python3.16+0x654aec) #16 pythread_wrapper /home/someuser/projects/cpython/cpython-upstream-main/Python/thread_pthread.h:234:5 (python3.16+0x574def) Issue: gh-154937

Open Graph Description: Issue Close #154937 Proposed Changes The ThreadHandle.ident should be guarded by ThreadHandle.mutex as the below comment. cpython/Modules/_threadmodule.c Lines 132 ...

X Description: Issue Close #154937 Proposed Changes The ThreadHandle.ident should be guarded by ThreadHandle.mutex as the below comment. cpython/Modules/_threadmodule.c Lines 132 ...

Opengraph URL: https://github.com/python/cpython/pull/155085

X: @github

direct link

Domain: github.com

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/:user_id/:repository/pull/:id/files(.:format)
route-controllerpull_requests
route-actionfiles
fetch-noncev2:0e72fb33-2643-013f-63a1-c9838a6139b6
current-catalog-service-hashae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b
request-idA02E:21DFED:630013:7D41AD:6B020A3D
html-safe-nonceeab00d8754c62b68c3d0f158bd35e5d046f8f162b8aa19a4f4423959cd6f6a1e
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMDJFOjIxREZFRDo2MzAwMTM6N0Q0MUFEOjZCMDIwQTNEIiwidmlzaXRvcl9pZCI6IjE3MDI2MzM0MTcxMzQ0NDMwNzAiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac4c657028d75e29054a6f1824cd71a3aa8ca584d4e2b602202a95359220206770
hovercard-subject-tagpull_request:4188373583
github-keyboard-shortcutsrepository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///pull_requests/show/files
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/python/cpython/pull/155085/files
twitter:imagehttps://avatars.githubusercontent.com/u/14014471?s=400&v=4
twitter:cardsummary_large_image
og:imagehttps://avatars.githubusercontent.com/u/14014471?s=400&v=4
og:image:altIssue Close #154937 Proposed Changes The ThreadHandle.ident should be guarded by ThreadHandle.mutex as the below comment. cpython/Modules/_threadmodule.c Lines 132 ...
og:site_nameGitHub
og:typeobject
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
diff-viewunified
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive full-width
disable-turbotrue
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/pull/155085/files#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fpull%2F155085%2Ffiles
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fpull%2F155085%2Ffiles
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fpull_requests%2Fshow%2Ffiles&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/pull/155085/files
Reloadhttps://github.com/python/cpython/pull/155085/files
Reloadhttps://github.com/python/cpython/pull/155085/files
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
Sign up for GitHub https://github.com/signup?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
terms of servicehttps://docs.github.com/terms
privacy statementhttps://docs.github.com/privacy
Sign inhttps://github.com/login?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
kumaraditya303https://github.com/kumaraditya303
python:mainhttps://github.com/python/cpython/tree/main
LindaSummer:fix/thread-ident-154937https://github.com/LindaSummer/cpython/tree/fix/thread-ident-154937
Conversation 13 https://github.com/python/cpython/pull/155085
Commits 8 https://github.com/python/cpython/pull/155085/commits
Checks 67 https://github.com/python/cpython/pull/155085/checks
Files changed 2 https://github.com/python/cpython/pull/155085/files
gh-154937: Fix _thread._shutdown() racing with _thread.start_joinable_thread on ThreadHandle.ident https://github.com/python/cpython/pull/155085/files#top
Show all changes 8 commits https://github.com/python/cpython/pull/155085/files
3e24b32 fix ident mutex issue LindaSummer Jul 31, 2026 https://github.com/python/cpython/pull/155085/commits/3e24b32244439911bdcf89b70ea61fe8411dd0e7
b8d8dfc add unit test case LindaSummer Aug 2, 2026 https://github.com/python/cpython/pull/155085/commits/b8d8dfca869ad0606ad77f1c9fd1a2f5c637b904
266ced2 add blurb LindaSummer Aug 2, 2026 https://github.com/python/cpython/pull/155085/commits/266ced261fc8e6221b982ff38b4f95e11f983091
4384239 follow copliot comment and reduce concurrent threads count LindaSummer Aug 2, 2026 https://github.com/python/cpython/pull/155085/commits/4384239289e9d9bd6884151e6bdd8f9d1c24704a
3efdf4f fix the import and newline for comment LindaSummer Aug 3, 2026 https://github.com/python/cpython/pull/155085/commits/3efdf4fd0198b18e92f2b13ef6521fb06a15738a
968a8d1 Merge branch 'main' into fix/thread-ident-154937 LindaSummer Aug 3, 2026 https://github.com/python/cpython/pull/155085/commits/968a8d1e33bcc0da6a66cc1b683347a8782aaefb
2f0a2eb remove the heavy unit test which launches 4*1_000 os threads LindaSummer Aug 3, 2026 https://github.com/python/cpython/pull/155085/commits/2f0a2ebff4daaec0fe84ce61231d932bc75c7184
2d311ce Merge branch 'main' into fix/thread-ident-154937 LindaSummer Aug 3, 2026 https://github.com/python/cpython/pull/155085/commits/2d311cea73140214f18810c41013f1c3f03ffeb8
Clear filters https://github.com/python/cpython/pull/155085/files
Please reload this pagehttps://github.com/python/cpython/pull/155085/files
Please reload this pagehttps://github.com/python/cpython/pull/155085/files
2026-08-02-17-55-29.gh-issue-154937.m9IBba.rst https://github.com/python/cpython/pull/155085/files#diff-6764f2e7fdf03ef35834d839d601f6f20d3681425b2dfdf13ee2899189e3caa9
_threadmodule.c https://github.com/python/cpython/pull/155085/files#diff-23071700ee893f365a4c117210b9129d4ac6afe5cc6e52bb5cd4cabbc6816e07
Misc/NEWS.d/next/Core_and_Builtins/2026-08-02-17-55-29.gh-issue-154937.m9IBba.rsthttps://github.com/python/cpython/pull/155085/files#diff-6764f2e7fdf03ef35834d839d601f6f20d3681425b2dfdf13ee2899189e3caa9
View file https://github.com/LindaSummer/cpython/blob/2d311cea73140214f18810c41013f1c3f03ffeb8/Misc/NEWS.d/next/Core_and_Builtins/2026-08-02-17-55-29.gh-issue-154937.m9IBba.rst
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/155085/{{ revealButtonHref }}
Modules/_threadmodule.chttps://github.com/python/cpython/pull/155085/files#diff-23071700ee893f365a4c117210b9129d4ac6afe5cc6e52bb5cd4cabbc6816e07
View file https://github.com/LindaSummer/cpython/blob/2d311cea73140214f18810c41013f1c3f03ffeb8/Modules/_threadmodule.c
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/155085/{{ revealButtonHref }}
https://github.com/python/cpython/pull/155085/files#diff-23071700ee893f365a4c117210b9129d4ac6afe5cc6e52bb5cd4cabbc6816e07
https://github.com/python/cpython/pull/155085/files#diff-23071700ee893f365a4c117210b9129d4ac6afe5cc6e52bb5cd4cabbc6816e07
Please reload this pagehttps://github.com/python/cpython/pull/155085/files
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.