python / python/cpython

Add a `PyThreadState *` parameter (almost) everywhere

Open
#132,312 14 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core performance topic-C-API type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

This is part feature request, part performance issue and part a general appeal for assistance.

We should add a new variant taking a PyThreadState * parameter for most C API and internal functions.

There are two motivations for this, performance and a future, consistent C API.

Performance

The PyThreadState struct is ubiquitous in the VM, it controls stack usage, holds the freelists, holds the current exception, etc, etc.

Consequently many C functions, both API and internal, take a PyThreadState *tstate parameter.
However, for historical reasons, many C functions, both API and internal, do not such a parameter.

This leads to some fairly easy to fix inefficiencies, where spam() and eggs() take a thread state, but ham() does not, then spam() calls ham() which calls eggs(), forcing ham() to load the thread state from thread local storage, in order to pass it to eggs().
Adding a PyThreadState *tstate to ham() avoids need to access thread local storage.

Consistent, portable, future looking C API

In order to support things like tagged integers, we are going to need to a new C API.

It is out of scope to discuss what such an API would look like, but all realistic proposal so far take a "context" parameter to all, or almost all, API functions. Using a PyThreadState * parameter everywhere would make a mechanical transformation from old to new API much simpler.

Unfortunately the C API is large and cannot be changed, so we will need many new functions, like ham_tstate() which replicates ham() but with a thread state parameter.

This work is largely mechanical, and can be done by inexperienced contributors. Hence the appeal for assistance.

Linked PRs
  • gh-151453

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no specific files, tests, or entry points; start by reviewing linked PR gh-151453 and the C API and internal functions it covers. Done means the agreed scope has corresponding PyThreadState-aware variants and the selected work is complete.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.