python / python/cpython

Add a private API to defer automatic garbage collection

Aperta
#153,946 10 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

interpreter-core type-feature
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

I would like to propose a private API that allows CPython internals to defer automatic garbage collection on the current thread without changing the interpreter-visible GC state.

Some CPython internals build large object graphs in a burst, where a collection triggered halfway through cannot reclaim anything from that operation and only traverses a half-built graph. Using PyGC_Disable() for this changes interpreter-wide state. Saving and restoring that state is racy in the free-threaded build, and it can also be observed or changed by user code in the GIL build.

What we want is something approximately like:

_PyGC_DeferAutomaticCollection(tstate);
/* Build a large object graph. */
_PyGC_ResumeAutomaticCollection(tstate);

This would be a private CPython API. It should be per-thread and nestable, keep allocation counters running, leave gc.isenabled() unchanged, and defer only automatic collection. Leaving the outermost scope would schedule a collection if one became due.

I think there are many possible cases in the stdlib and core that can benefit from this, and we currently do not have a safe tool for them. This can be implemented with a small nesting counter in _PyThreadStateImpl, checked by the allocation paths and _Py_RunGC(). This would allow these optimizations without changing user-visible GC state or introducing cross-thread races.

Linked PRs
  • gh-154188

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia esaminando _PyThreadStateImpl, i percorsi di allocazione e _Py_RunGC(), che la proposta identifica come punti di ingresso rilevanti. L’implementazione deve supportare l’annidamento per thread, preservare i contatori delle allocazioni e gc.isenabled(), rimandare solo la raccolta automatica e pianificare una raccolta dovuta quando riprende l’ambito più esterno.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
c, python
Ambito
backend
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.