Repository navigation
Thread safety of PyCapsule #145563
Copy link
Copy link
Closed
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)topic-C-APItype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Description
Activity
- addedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Mar 5, 2026 It seems fine to me to require that callers to the capsule API are required to do their own synchronization.
Reacted by Sebastian BergIt seems fine to me to require that callers to the capsule API are required to do their own synchronization.
To be clear: does that mean we also do not add atomic reads/writes to the
pointerinPyCapsule_GetPointer?- addedinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)
on Mar 5, 2026 Yes
Reacted by Sebastian BergShould we update the document to include a thread-safety notice for users, if we want callers to ensure thread safety?
Reacted by Sebastian Berg#145255 will add a mechanism for thread safety notices.
- added a commit that references this issue
on Mar 31, 2026
Metadata
Metadata
Assignees
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)topic-C-APItype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Bug report
Bug description:
The
PyCapsuleobject is not thread-safe. For example the read and write operations to the underlyingpointerdo not use atomics.cpython/Objects/capsule.c
Line 111 in e094544
This can be fixed with atomic read and write operations. (same for the
namefield and some others)Another potential issue is that some operations on a capsule are not atomic. For example a thread can attempt to retrieve a pointer using
PyCapsule_GetPointerwhile a concurrent thread is updating the name and pointer usingPyCapsule_SetNameandPyCapsule_SetPointer. That could be addressed with locks, but I suspect that is too heavy for the capsule object.I am leaning towards adding atomics for the read and write operations and documenting that in a PyCapsule does not guarantee its methods are atomic.
@colesbury @seberg
CPython versions tested on:
CPython main branch
Operating systems tested on:
Windows
Linked PRs