python / python/cpython

Add optional `wait_if_running` argument to `gc.collect()`

オープン
#137,682 コメント 4 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

interpreter-core type-feature
主要言語
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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

gc.collect() のドキュメントと、提案の現在の動作および要求されている動作から始めます。gc.collect() の実装とその garbage collection のエントリーポイントをたどり、並行または再入可能な collection に関する既存のテストを特定します。keyword-only オプションがデフォルトの動作を維持し、別のスレッドによる collection を待機し、同じスレッドからの再入に対して例外を発生させれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
機能追加
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。