python / python/cpython

PyErr_CheckSignals should be callable without holding the GIL

未關閉
#133,465 3 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core topic-C-API type-feature
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Feature or enhancement

Proposal:

Compiled-code modules that implement time-consuming operations that don’t require manipulating Python objects, are supposed to call PyErr_CheckSignals frequently throughout each such operation, so that if the user interrupts the operation with control-C, it is cancelled promptly.

In the normal case where no signals are pending, PyErr_CheckSignals is cheap; however, callers must hold the GIL, and compiled-code modules that implement time-consuming operations are also supposed to release the GIL during each such operation. The overhead of reclaiming the GIL in order to call PyErr_CheckSignals,
and then releasing it again, sufficiently often for reasonable user responsiveness, can be substantial.

If my understanding of the thread-state rules is correct, PyErr_CheckSignals only needs the GIL if it has work to do. Checking whether there is a pending signal, or a pending request to run the cycle collector, requires only a couple of atomic loads. Therefore, I propose that we should restructure PyErr_CheckSignals and its close relatives (_PyErr_CheckSignals and _PyErr_CheckSignalsTstate) so that all the “do we have anything to do” checks are done in a batch before anything that needs the GIL. If any of them are true, then the function should acquire the GIL itself, repeat the check (because another thread could have stolen the event while we were waiting for the GIL), and then actually do the work, thus enabling callers to not hold the GIL.

I have already prepared and tested an implementation of this change and will submit a PR shortly.

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

Linked PRs
  • gh-133466
  • gh-135358
  • gh-140549

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

檢查 gh-133466、gh-135358 和 gh-140549 中連結的工作,然後追蹤 PyErr_CheckSignals 及其相關的 _PyErr_CheckSignals 和 _PyErr_CheckSignalsTstate。檢查待處理工作檢查和依賴 GIL 的處理是如何分離的;完成的標準是,呼叫方可以在不持有 GIL 的情況下進行檢查,而所需工作仍會取得 GIL 並重新檢查。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
c, python
領域
api, backend
Issue 類型
功能
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。