Skip to content

Commit c929bc0

Browse files
committed
gh-111926 Update _weakref to be threadsafe in --disable-gil build
1 parent bd89bca commit c929bc0

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

Modules/_weakref.c

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#include "Python.h"
2-
#include "pycore_dict.h" // _PyDict_DelItemIf()
3-
#include "pycore_object.h" // _PyObject_GET_WEAKREFS_LISTPTR
4-
#include "pycore_weakref.h" // _PyWeakref_IS_DEAD()
5-
2+
#include "pycore_dict.h" // _PyDict_DelItemIf()
3+
#include "pycore_object.h" // _PyObject_GET_WEAKREFS_LISTPTR
4+
#include "pycore_weakref.h" // _PyWeakref_IS_DEAD()
5+
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION
66

77
#define GET_WEAKREFS_LISTPTR(o) \
88
((PyWeakReference **) _PyObject_GET_WEAKREFS_LISTPTR(o))
@@ -32,9 +32,11 @@ _weakref_getweakrefcount_impl(PyObject *module, PyObject *object)
3232

3333
if (!_PyType_SUPPORTS_WEAKREFS(Py_TYPE(object)))
3434
return 0;
35-
35+
Py_BEGIN_CRITICAL_SECTION(object);
3636
list = GET_WEAKREFS_LISTPTR(object);
37-
return _PyWeakref_GetWeakrefCount(*list);
37+
Py_ssize_t count = _PyWeakref_GetWeakrefCount(*list);
38+
Py_END_CRITICAL_SECTION();
39+
return count;
3840
}
3941

4042

@@ -94,6 +96,7 @@ _weakref_getweakrefs(PyObject *module, PyObject *object)
9496
return PyList_New(0);
9597
}
9698

99+
Py_BEGIN_CRITICAL_SECTION(object);
97100
PyWeakReference **list = GET_WEAKREFS_LISTPTR(object);
98101
Py_ssize_t count = _PyWeakref_GetWeakrefCount(*list);
99102

@@ -107,6 +110,7 @@ _weakref_getweakrefs(PyObject *module, PyObject *object)
107110
PyList_SET_ITEM(result, i, Py_NewRef(current));
108111
current = current->wr_next;
109112
}
113+
Py_END_CRITICAL_SECTION();
110114
return result;
111115
}
112116

0 commit comments

Comments
 (0)