python / python/cpython

Py_(X)SETREF should have atomic versions on free-threaded builds

未關閉
#150,044 4 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

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

描述

Feature or enhancement

Proposal:

Right now, Py_SETREF is implemented in non-atomic terms, which makes it subject to operation reordering issues on weakly ordered architectures (which caused a problem fixing gh-149816, where even switching from separate Py_CLEAR and later assignment to set_sni_cb to a single "atomic" Py_SETREF didn't fix the issue on ARM, because SSL's callback was being invoked asynchronously).

Py_SETREF is naturally implemented in terms of an atomic exchange, and at least for the free-threaded builds, it seems like it should be implemented as such to avoid such raciness, supplementing the existing:

#ifdef _Py_TYPEOF
#define Py_SETREF(dst, src) \
    do { \
        _Py_TYPEOF(dst)* _tmp_dst_ptr = &(dst); \
        _Py_TYPEOF(dst) _tmp_old_dst = (*_tmp_dst_ptr); \
        *_tmp_dst_ptr = (src); \
        Py_DECREF(_tmp_old_dst); \
    } while (0)
#else
#define Py_SETREF(dst, src) \
    do { \
        PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
        PyObject *_tmp_old_dst = (*_tmp_dst_ptr); \
        PyObject *_tmp_src = _PyObject_CAST(src); \
        memcpy(_tmp_dst_ptr, &_tmp_src, sizeof(PyObject*)); \
        Py_DECREF(_tmp_old_dst); \
    } while (0)
#endif

// Similarly long nonsense for Py_XSETREF

with a new atomic-based approach for free-threaded builds:

#define Py_SETREF(dst, src) Py_DECREF(_Py_atomic_exchange_ptr(&(dst), (src)))
#define Py_XSETREF(dst, src) Py_XDECREF(_Py_atomic_exchange_ptr(&(dst), (src)))

Please poke holes in this approach. I have a lot of experience with writing multithreaded C code, but will never be convinced I've covered every race condition no matter how simple the code.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

找出 Py_SETREF 和 Py_XSETREF 的 CPython C API 定義,接著檢查 free-threaded 建置如何選擇它們的實作。根據此處所述的所有權與記憶體排序疑慮,評估所提議的原子交換;完成的標準是達成經過審查的決策,並透過適當的驗證來實作或拒絕此方法。

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

評估

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

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

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