Skip to content

Commit 573d890

Browse files
committed
add thread test
1 parent a16846d commit 573d890

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/random.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,38 @@ mod tests {
234234
})
235235
}
236236

237+
/// More complex version of primary use case: use from multiple threads
238+
#[cfg(feature = "rand")]
239+
#[test]
240+
fn use_parallel() -> PyResult<()> {
241+
use crate::array::{PyArray2, PyArrayMethods as _};
242+
use ndarray::Dimension;
243+
use rand::Rng;
244+
use std::sync::{Arc, Mutex};
245+
246+
Python::with_gil(|py| -> PyResult<_> {
247+
let mut arr = PyArray2::<u32>::zeros(py, (2, 300), false).readwrite();
248+
let bitgen = get_bit_generator(py)?.lock()?;
249+
let bitgen = Arc::new(Mutex::new(bitgen));
250+
251+
let (_n_threads, chunk_size) = arr.dims().into_pattern();
252+
let slice = arr.as_slice_mut()?;
253+
254+
Python::allow_threads(py, || {
255+
std::thread::scope(|s| {
256+
for chunk in slice.chunks_exact_mut(chunk_size) {
257+
let bitgen = Arc::clone(&bitgen);
258+
s.spawn(move || {
259+
let mut bitgen = bitgen.lock().unwrap();
260+
chunk.fill_with(|| bitgen.random_range(10..200));
261+
});
262+
}
263+
})
264+
});
265+
Ok(())
266+
})
267+
}
268+
237269
/// Test that the `rand::Rng` APIs work
238270
#[cfg(feature = "rand")]
239271
#[test]

0 commit comments

Comments
 (0)