Skip to content

Missing critical sections for PyDict_Next calls in _functoolsmodule.c #145446

Description

@brijkapadia

Bug report

Bug description:

After some discussion on PR #145362, I noticed that in Modules/_functoolsmodule.c, all use cases of PyDict_Next do not use a critical section, which is necessary in for the free-threaded build. The docs say that for PyDict_Next:

The function is not thread-safe in the free-threaded build without external synchronization. You can use Py_BEGIN_CRITICAL_SECTION to lock the dictionary while iterating over it

I have not checked if other files are missing a critical section, but it is definitely possible. I will draft a PR shortly for this issue in the coming days, but if anyone else finds other occurrences of PyDict_Next that are not thread-safe, please let me know.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. aisk commented on Mar 3, 2026

    @aisk
  2. added
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    type-featureA feature request or enhancement
    and removed
    type-bugAn unexpected behavior, bug, or error
    on Mar 3, 2026
  3. aisk commented on Mar 3, 2026

    @aisk
  4. added
    pendingThe issue will be closed if no feedback is provided
    on Mar 3, 2026
  5. aisk commented on Mar 3, 2026

    @aisk
    Member

    Sorry, I re-read your issue, you mean make _functoolsmodule thread-safe when calling PyDict_Next by adding a critical section? The title is a little bit misleading 😂 Updated the title, and please feel free to modify it if I'm wrong.

  6. reopened this on Mar 3, 2026
  7. changed the title [-]Make PyDict_Next thread-safe using a critical section[/-] [+]Missing critical sections for `PyDict_Next` calls in `_functoolsmodule.c`[/+] on Mar 3, 2026
  8. added
    type-bugAn unexpected behavior, bug, or error
    and removed
    type-featureA feature request or enhancement
    pendingThe issue will be closed if no feedback is provided
    on Mar 3, 2026
  9. brijkapadia commented on Mar 3, 2026

    @brijkapadia
    ContributorAuthor

    Yes, sorry if I was not clear. I meant to wrap calls to PyDict_Next specifically in _functools_module in a critical section, not to add a critical section inside PyDict_Next. Thank you for changing the title.

  10. added a commit that references this issue on Mar 12, 2026
  11. added a commit that references this issue on Mar 12, 2026
  12. added a commit that references this issue on Mar 13, 2026
  13. 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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions