Skip to content

Commit c0f3fcf

Browse files
gh-160978: Return the same ctypes array type when created concurrently (#161494)
1 parent b09a7e9 commit c0f3fcf

3 files changed

Lines changed: 131 additions & 18 deletions

File tree

‎Lib/test/test_ctypes/test_arrays.py‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import ctypes
22
import sys
3+
import threading
34
import unittest
5+
from concurrent.futures import ThreadPoolExecutor
46
from ctypes import (Structure, Array, ARRAY, sizeof, addressof,
57
create_string_buffer, create_unicode_buffer,
68
c_char, c_wchar, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
79
c_long, c_ulonglong, c_float, c_double, c_longdouble)
8-
from test.support import bigmemtest, _2G, threading_helper, Py_GIL_DISABLED
10+
from test.support import (bigmemtest, _2G, threading_helper,
11+
Py_GIL_DISABLED, SHORT_TIMEOUT)
912
from ._support import (_CData, PyCArrayType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
1013
Py_TPFLAGS_IMMUTABLETYPE)
1114

@@ -288,5 +291,49 @@ def run():
288291
raise cm.exc_value
289292

290293

294+
class ArrayTypeCacheTest(unittest.TestCase):
295+
# gh-160978: the array type cache could hand out distinct type objects for
296+
# the same (item type, length) pair when the array type was created from
297+
# more than one thread at a time.
298+
299+
@threading_helper.requires_working_threading()
300+
def test_concurrent_creation_with_set_name(self):
301+
# Creating the array type runs Python code -- ``__set_name__`` here --
302+
# which lets a second thread reach the cache before the first one has
303+
# stored its type. Without the fix this fails on the default build as
304+
# well, so it guards the fix even where threads cannot interleave
305+
# freely.
306+
barrier = threading.Barrier(2)
307+
308+
class Meta(type(c_int)):
309+
def __set_name__(cls, owner, name):
310+
barrier.wait(timeout=SHORT_TIMEOUT)
311+
312+
class Item(c_int, metaclass=Meta):
313+
pass
314+
315+
with ThreadPoolExecutor(2) as pool:
316+
first, second = pool.map(lambda _: Item * 100, range(2))
317+
318+
self.assertIs(first, second)
319+
# Raises TypeError if the two types are distinct.
320+
first.from_param(second())
321+
322+
@threading_helper.requires_working_threading()
323+
def test_concurrent_creation_returns_identical_types(self):
324+
nthreads = 8
325+
barrier = threading.Barrier(nthreads)
326+
327+
def make_type(length):
328+
barrier.wait(timeout=SHORT_TIMEOUT)
329+
return c_int * length
330+
331+
with ThreadPoolExecutor(nthreads) as pool:
332+
for length in range(1, 51):
333+
types = list(pool.map(make_type, [length] * nthreads))
334+
barrier.reset()
335+
self.assertEqual(len(set(types)), 1)
336+
337+
291338
if __name__ == '__main__':
292339
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :mod:`ctypes` handing out distinct array types for the same item type
2+
and length when the array type is created concurrently from several
3+
threads.

‎Modules/_ctypes/_ctypes.c‎

Lines changed: 80 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,23 @@ _DictRemover_call(PyObject *myself, PyObject *args, PyObject *kw)
186186
{
187187
DictRemoverObject *self = _DictRemoverObject_CAST(myself);
188188
if (self->key && self->dict) {
189-
if (-1 == PyDict_DelItem(self->dict, self->key)) {
189+
/* Only remove the entry if it is still the proxy that died: the
190+
key may have been reused for a new object in the meantime. */
191+
PyObject *proxy = PyTuple_GET_SIZE(args) == 1
192+
? PyTuple_GET_ITEM(args, 0) : NULL;
193+
PyObject *current;
194+
int rc;
195+
Py_BEGIN_CRITICAL_SECTION(self->dict);
196+
rc = PyDict_GetItemRef(self->dict, self->key, &current);
197+
if (rc == 1) {
198+
rc = 0;
199+
if (current == proxy) {
200+
rc = PyDict_DelItem(self->dict, self->key);
201+
}
202+
Py_DECREF(current);
203+
}
204+
Py_END_CRITICAL_SECTION();
205+
if (rc < 0) {
190206
PyErr_FormatUnraisable("Exception ignored while "
191207
"calling _ctypes.DictRemover");
192208
}
@@ -215,32 +231,72 @@ static PyType_Spec dictremover_spec = {
215231
.slots = dictremover_slots,
216232
};
217233

218-
int
219-
PyDict_SetItemProxy(ctypes_state *st, PyObject *dict, PyObject *key, PyObject *item)
234+
/* Cache `item` in `dict` under `key` through a weakref proxy, unless a live
235+
entry already exists. On success *presult is a new reference to whatever
236+
is cached for `key` afterwards: `item` itself, or the object another
237+
thread cached first.
238+
Returns 0 on success, -1 with an exception set on failure. */
239+
static int
240+
_PyDict_SetDefaultItemProxy(ctypes_state *st, PyObject *dict, PyObject *key,
241+
PyObject *item, PyObject **presult)
220242
{
221-
PyObject *obj;
222-
DictRemoverObject *remover;
223-
PyObject *proxy;
224-
int result;
225-
226-
obj = _PyObject_CallNoArgs((PyObject *)st->DictRemover_Type);
227-
if (obj == NULL)
243+
PyObject *obj = _PyObject_CallNoArgs((PyObject *)st->DictRemover_Type);
244+
if (obj == NULL) {
228245
return -1;
246+
}
229247

230-
remover = (DictRemoverObject *)obj;
248+
DictRemoverObject *remover = (DictRemoverObject *)obj;
231249
assert(remover->key == NULL);
232250
assert(remover->dict == NULL);
233251
remover->key = Py_NewRef(key);
234252
remover->dict = Py_NewRef(dict);
235253

236-
proxy = PyWeakref_NewProxy(item, obj);
254+
PyObject *proxy = PyWeakref_NewProxy(item, obj);
237255
Py_DECREF(obj);
238-
if (proxy == NULL)
256+
if (proxy == NULL) {
257+
return -1;
258+
}
259+
260+
PyObject *stored;
261+
int present = PyDict_SetDefaultRef(dict, key, proxy, &stored);
262+
if (present < 0) {
263+
Py_DECREF(proxy);
239264
return -1;
265+
}
266+
if (present == 0) {
267+
/* Our proxy was inserted; `item` is the canonical object. */
268+
Py_DECREF(stored);
269+
Py_DECREF(proxy);
270+
*presult = Py_NewRef(item);
271+
return 0;
272+
}
240273

241-
result = PyDict_SetItem(dict, key, proxy);
274+
/* Another thread cached an object for this key first. Prefer it, so that
275+
every caller gets the same object. */
276+
PyObject *existing = NULL;
277+
int rc = 0;
278+
if (PyWeakref_CheckProxy(stored)) {
279+
rc = PyWeakref_GetRef(stored, &existing);
280+
}
281+
Py_DECREF(stored);
282+
if (rc < 0) {
283+
Py_DECREF(proxy);
284+
return -1;
285+
}
286+
if (existing != NULL) {
287+
Py_DECREF(proxy);
288+
*presult = existing;
289+
return 0;
290+
}
291+
292+
/* The cached entry had already been cleared; install ours instead. */
293+
rc = PyDict_SetItem(dict, key, proxy);
242294
Py_DECREF(proxy);
243-
return result;
295+
if (rc < 0) {
296+
return -1;
297+
}
298+
*presult = Py_NewRef(item);
299+
return 0;
244300
}
245301

246302
static int
@@ -5434,13 +5490,20 @@ PyCArrayType_from_ctype(ctypes_state *st, PyObject *itemtype, Py_ssize_t length)
54345490
Py_DECREF(key);
54355491
return NULL;
54365492
}
5437-
if (PyDict_SetItemProxy(st, st->array_cache, key, result) < 0) {
5493+
PyObject *cached;
5494+
int rc;
5495+
Py_BEGIN_CRITICAL_SECTION(st->array_cache);
5496+
rc = _PyDict_SetDefaultItemProxy(st, st->array_cache, key, result,
5497+
&cached);
5498+
Py_END_CRITICAL_SECTION();
5499+
if (rc < 0) {
54385500
Py_DECREF(key);
54395501
Py_DECREF(result);
54405502
return NULL;
54415503
}
54425504
Py_DECREF(key);
5443-
return result;
5505+
Py_DECREF(result);
5506+
return cached;
54445507
}
54455508

54465509

0 commit comments

Comments
 (0)