mirror of
https://github.com/python/cpython.git
synced 2025-08-04 08:59:19 +00:00
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.
This commit is contained in:
parent
d24d1c986d
commit
7e38e6745d
4 changed files with 61 additions and 1 deletions
|
@ -2971,7 +2971,8 @@ zip_next(zipobject *lz)
|
|||
|
||||
if (tuplesize == 0)
|
||||
return NULL;
|
||||
if (Py_REFCNT(result) == 1) {
|
||||
|
||||
if (_PyObject_IsUniquelyReferenced(result)) {
|
||||
Py_INCREF(result);
|
||||
for (i=0 ; i < tuplesize ; i++) {
|
||||
it = PyTuple_GET_ITEM(lz->ittuple, i);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue