Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions Include/internal/pycore_weakref.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,26 +74,27 @@ static inline PyObject* _PyWeakref_GET_REF(PyObject *ref_obj)
assert(PyWeakref_Check(ref_obj));
PyWeakReference *ref = _Py_CAST(PyWeakReference*, ref_obj);

PyObject *obj = FT_ATOMIC_LOAD_PTR(ref->wr_object);
#ifdef Py_GIL_DISABLED
PyObject *obj = _Py_atomic_load_ptr(&ref->wr_object);
if (obj == Py_None) {
// clear_weakref() was called
return NULL;
}

LOCK_WEAKREFS(obj);
#ifdef Py_GIL_DISABLED
if (ref->wr_object == Py_None) {
if (_Py_TryIncrefCompare(&ref->wr_object, obj)) {
return obj;
}
return NULL;
#else
PyObject *obj = ref->wr_object;
if (obj == Py_None) {
// clear_weakref() was called
UNLOCK_WEAKREFS(obj);
return NULL;
}
#endif
if (_Py_TryIncref(obj)) {
UNLOCK_WEAKREFS(obj);
return obj;
}
UNLOCK_WEAKREFS(obj);
return NULL;
#endif
}

static inline int _PyWeakref_IS_DEAD(PyObject *ref_obj)
Expand All @@ -108,8 +109,8 @@ static inline int _PyWeakref_IS_DEAD(PyObject *ref_obj)
}
else {
LOCK_WEAKREFS(obj);
// See _PyWeakref_GET_REF() for the rationale of this test
#ifdef Py_GIL_DISABLED
// The weakref may have been cleared before the lock was acquired.
ret = (ref->wr_object == Py_None) || _is_dead(obj);
#else
ret = _is_dead(obj);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Improve the performance and thread scaling of dereferencing weak references
in the :term:`free-threaded build`. Dereferencing a weak reference no longer
takes a lock.
4 changes: 2 additions & 2 deletions Objects/weakrefobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ clear_weakref_lock_held(PyWeakReference *self, PyObject **callback)
/* If 'self' is the end of the list (and thus self->wr_next ==
NULL) then the weakref list itself (and thus the value of *list)
will end up being set to NULL. */
FT_ATOMIC_STORE_PTR(*list, self->wr_next);
FT_ATOMIC_STORE_PTR_RELEASE(*list, self->wr_next);
}
FT_ATOMIC_STORE_PTR(self->wr_object, Py_None);
FT_ATOMIC_STORE_PTR_RELEASE(self->wr_object, Py_None);
if (self->wr_prev != NULL) {
self->wr_prev->wr_next = self->wr_next;
}
Expand Down
Loading