Add optional `wait_if_running` argument to `gc.collect()`
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
Feature or enhancement
Background
The gc.collect() documentation states:
The effect of calling
gc.collect()while the interpreter is already performing a collection is undefined.
In practice, gc.collect() will return immediately if it's already running, including re-entrant calls from the same thread (i.e., from object finalizers) and if the GC happens to be running in another thread. Note that even with the GIL, the GC isn't completely atomic: running tp_clear and object finalizes (i.e., __del__ functions) can release the GIL and allow another thread to run concurrently.
Motivation
Both CPython and third-party packages often use gc.collect() in tests to ensure that cycles are collected and, in the free threading build, any delayed reference count operations are processed when testing for things related to object lifetimes.
The problem is that these tests can be flaky if multiple threads are used, because if one thread happens to be running the GC, then the gc.collect() in another thread returns immediately without doing anything. This happens more frequently in the free threading build because there are more opportunities for interleaving between threads and because of things like biased reference counting that can lead to delayed object destructors.
Proposal
Add a keyword-only argument wait_if_running to gc.collect(). The default value is wait_if_running=False, which preserves the current behavior. If wait_if_running=True:
- If the GC is running in a different thread, then the call will wait until that GC finishes and then run the GC.
- If the GC is running in the caller's thread, then the call will raise an exception so as to avoid deadlock.
cc @hawkinsp
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 gc.collect() 的文件以及提案目前的行為和要求的行為開始。追蹤 gc.collect() 的實作及其 garbage collection 入口點,然後找出現有的並行或可重入 collection 測試。當 keyword-only 選項保留預設行為、等待另一個執行緒的 collection,並在同一個執行緒重新進入時引發例外,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 功能
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100