File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff 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]
You can’t perform that action at this time.
0 commit comments