Visitar URL original
Thread safety of PyCapsule · Issue #145563 · python/cpython · GitHub
Skip to content

Thread safety of PyCapsule #145563

Description

@eendebakpt

Bug report

Bug description:

The PyCapsule object is not thread-safe. For example the read and write operations to the underlying pointer do not use atomics.

return capsule->pointer;

This can be fixed with atomic read and write operations. (same for the name field 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_GetPointer while a concurrent thread is updating the name and pointer using PyCapsule_SetName and PyCapsule_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

Activity

  1. colesbury commented on Mar 5, 2026

    @colesbury
    Contributor

    It seems fine to me to require that callers to the capsule API are required to do their own synchronization.

  2. eendebakpt commented on Mar 5, 2026

    @eendebakpt
    ContributorAuthor

    It 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 pointer in PyCapsule_GetPointer?

  3. colesbury commented on Mar 5, 2026

    @colesbury
    Contributor

    Yes

  4. aisk commented on Mar 6, 2026

    @aisk
    Member

    Should we update the document to include a thread-safety notice for users, if we want callers to ensure thread safety?

  5. encukou commented on Mar 11, 2026

    @encukou
    Member

    #145255 will add a mechanism for thread safety notices.

  6. added a commit that references this issue on Mar 31, 2026
  7. added a commit that references this issue on Mar 31, 2026
  8. added a commit that references this issue on Mar 31, 2026
  9. added a commit that references this issue on Apr 16, 2026
  10. added a commit that references this issue on Apr 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-C-APItype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions