|
1 | 1 | import ctypes |
2 | 2 | import sys |
| 3 | +import threading |
3 | 4 | import unittest |
| 5 | +from concurrent.futures import ThreadPoolExecutor |
4 | 6 | from ctypes import (Structure, Array, ARRAY, sizeof, addressof, |
5 | 7 | create_string_buffer, create_unicode_buffer, |
6 | 8 | c_char, c_wchar, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, |
7 | 9 | 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) |
9 | 12 | from ._support import (_CData, PyCArrayType, Py_TPFLAGS_DISALLOW_INSTANTIATION, |
10 | 13 | Py_TPFLAGS_IMMUTABLETYPE) |
11 | 14 |
|
@@ -288,5 +291,49 @@ def run(): |
288 | 291 | raise cm.exc_value |
289 | 292 |
|
290 | 293 |
|
| 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 | + |
291 | 338 | if __name__ == '__main__': |
292 | 339 | unittest.main() |
0 commit comments