]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-123271: Make builtin zip method safe under free-threading (#123272)
authorPieter Eendebak <pieter.eendebak@gmail.com>
Tue, 27 Aug 2024 19:22:43 +0000 (21:22 +0200)
committerGitHub <noreply@github.com>
Tue, 27 Aug 2024 19:22:43 +0000 (15:22 -0400)
commit7e38e6745d2f9ee235d934ab7f3c6b3085be2b70
tree3024532b4fd63cf883495b59259e0dd431175992
parentd24d1c986d2c55933f89c6b73b2e618448115f54
gh-123271: Make builtin zip method safe under free-threading (#123272)

The `zip_next` function uses a common optimization technique for methods
that generate tuples. The iterator maintains an internal reference to
the returned tuple. When the method is called again, it checks if the
internal tuple's reference count is 1. If so, the tuple can be reused.
However, this approach is not safe under the free-threading build:
after checking the reference count, another thread may perform the same
check and also reuse the tuple. This can result in a double decref on
the items of the replaced tuple and a double incref (memory leak) on
the items of the tuple being set.

This adds a function, `_PyObject_IsUniquelyReferenced` that
encapsulates the stricter logic necessary for the free-threaded build:
the internal tuple must be owned by the current thread, have a local
refcount of one, and a shared refcount of zero.
Include/internal/pycore_object.h
Lib/test/test_free_threading/test_zip.py [new file with mode: 0644]
Misc/NEWS.d/next/Core_and_Builtins/2024-08-23-21-20-34.gh-issue-123271.xeVViR.rst [new file with mode: 0644]
Python/bltinmodule.c