Skip to content
Merged
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
7 changes: 6 additions & 1 deletion numpy/_core/src/multiarray/buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -793,8 +793,10 @@ array_getbuffer(PyObject *obj, Py_buffer *view, int flags)
}

/* Fill in information (and add it to _buffer_info if necessary) */
Py_BEGIN_CRITICAL_SECTION(self);
info = _buffer_get_info(
&((PyArrayObject_fields *)self)->_buffer_info, obj, flags);
Py_END_CRITICAL_SECTION();
if (info == NULL) {
goto fail;
}
Expand Down Expand Up @@ -880,7 +882,10 @@ void_getbuffer(PyObject *self, Py_buffer *view, int flags)
* to find the correct format. This format must also be stored, since
* at least in theory it can change (in practice it should never change).
*/
_buffer_info_t *info = _buffer_get_info(&scalar->_buffer_info, self, flags);
_buffer_info_t *info = NULL;
Py_BEGIN_CRITICAL_SECTION(scalar);
info = _buffer_get_info(&scalar->_buffer_info, self, flags);
Py_END_CRITICAL_SECTION();
if (info == NULL) {
Py_DECREF(self);
return -1;
Expand Down
29 changes: 29 additions & 0 deletions numpy/_core/tests/test_multithreading.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import concurrent.futures
import sys
import threading

import pytest
Expand Down Expand Up @@ -375,3 +376,31 @@ def replace_list_items(b):
finally:
if len(tasks) < 5:
b.abort()

@pytest.mark.skipif(sys.version_info < (3, 12), reason="Python >= 3.12 required")
def test_array__buffer__thread_safety():
import inspect
arr = np.arange(1000)
flags = [inspect.BufferFlags.STRIDED, inspect.BufferFlags.READ]

def func(b):
b.wait()
for i in range(100):
arr.__buffer__(flags[i % 2])

run_threaded(func, max_workers=8, pass_barrier=True)

@pytest.mark.skipif(sys.version_info < (3, 12), reason="Python >= 3.12 required")
def test_void_dtype__buffer__thread_safety():
import inspect
dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
x = np.array(('ndarray_scalar', (1.2, 3.0)), dtype=dt)[()]
assert isinstance(x, np.void)
flags = [inspect.BufferFlags.STRIDES, inspect.BufferFlags.READ]

def func(b):
b.wait()
for i in range(100):
x.__buffer__(flags[i % 2])

run_threaded(func, max_workers=8, pass_barrier=True)
Loading