Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit da95f8e

Browse files
authored
Merge pull request #26294 from ngoldbaum/disable-coercion-cache
MNT: disable the coercion cache for the nogil build
2 parents 1440eee + 1d976fc commit da95f8e

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

numpy/_core/src/multiarray/array_coercion.c

+12-3
Original file line numberDiff line numberDiff line change
@@ -615,10 +615,13 @@ update_shape(int curr_ndim, int *max_ndim,
615615
return success;
616616
}
617617

618-
618+
#ifndef Py_GIL_DISABLED
619619
#define COERCION_CACHE_CACHE_SIZE 5
620620
static int _coercion_cache_num = 0;
621621
static coercion_cache_obj *_coercion_cache_cache[COERCION_CACHE_CACHE_SIZE];
622+
#else
623+
#define COERCION_CACHE_CACHE_SIZE 0
624+
#endif
622625

623626
/*
624627
* Steals a reference to the object.
@@ -629,11 +632,14 @@ npy_new_coercion_cache(
629632
coercion_cache_obj ***next_ptr, int ndim)
630633
{
631634
coercion_cache_obj *cache;
635+
#if COERCION_CACHE_CACHE_SIZE > 0
632636
if (_coercion_cache_num > 0) {
633637
_coercion_cache_num--;
634638
cache = _coercion_cache_cache[_coercion_cache_num];
635639
}
636-
else {
640+
else
641+
#endif
642+
{
637643
cache = PyMem_Malloc(sizeof(coercion_cache_obj));
638644
}
639645
if (cache == NULL) {
@@ -662,11 +668,14 @@ npy_unlink_coercion_cache(coercion_cache_obj *current)
662668
{
663669
coercion_cache_obj *next = current->next;
664670
Py_DECREF(current->arr_or_sequence);
671+
#if COERCION_CACHE_CACHE_SIZE > 0
665672
if (_coercion_cache_num < COERCION_CACHE_CACHE_SIZE) {
666673
_coercion_cache_cache[_coercion_cache_num] = current;
667674
_coercion_cache_num++;
668675
}
669-
else {
676+
else
677+
#endif
678+
{
670679
PyMem_Free(current);
671680
}
672681
return next;
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import concurrent.futures
2+
3+
import numpy as np
4+
import pytest
5+
6+
from numpy.testing import IS_WASM
7+
8+
if IS_WASM:
9+
pytest.skip(allow_module_level=True, reason="no threading support in wasm")
10+
11+
12+
def test_parallel_errstate_creation():
13+
# if the coercion cache is enabled and not thread-safe, creating
14+
# RandomState instances simultaneously leads to a data race
15+
def func(seed):
16+
np.random.RandomState(seed)
17+
18+
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as tpe:
19+
futures = [tpe.submit(func, i) for i in range(500)]
20+
for f in futures:
21+
f.result()

0 commit comments

Comments
 (0)