Debian Codegraph @

debian/rust-vendor/rayon-core/src/scope/test.rs

raw
1 use crate::unwind;
2 use crate::ThreadPoolBuilder;
3 use crate::{scope, scope_fifo, Scope, ScopeFifo};
4 use rand::{Rng, SeedableRng};
5 use rand_xorshift::XorShiftRng;
6 use std::iter::once;
7 use std::sync::atomic::{AtomicUsize, Ordering};
8 use std::sync::{Barrier, Mutex};
9 use std::vec;
10
11 #[test]
12 fn scope_empty() {
13 scope(|_| {});
14 }
15
16 #[test]
17 fn scope_result() {
18 let x = scope(|_| 22);
19 assert_eq!(x, 22);
20 }
21
22 #[test]
23 fn scope_two() {
24 let counter = &AtomicUsize::new(0);
25 scope(|s| {
26 s.spawn(move |_| {
27 counter.fetch_add(1, Ordering::SeqCst);
28 });
29 s.spawn(move |_| {
30 counter.fetch_add(10, Ordering::SeqCst);
31 });
32 });
33
34 let v = counter.load(Ordering::SeqCst);
35 assert_eq!(v, 11);
36 }
37
38 #[test]
39 fn scope_divide_and_conquer() {
40 let counter_p = &AtomicUsize::new(0);
41 scope(|s| s.spawn(move |s| divide_and_conquer(s, counter_p, 1024)));
42
43 let counter_s = &AtomicUsize::new(0);
44 divide_and_conquer_seq(counter_s, 1024);
45
46 let p = counter_p.load(Ordering::SeqCst);
47 let s = counter_s.load(Ordering::SeqCst);
48 assert_eq!(p, s);
49 }
50
51 fn divide_and_conquer<'scope>(scope: &Scope<'scope>, counter: &'scope AtomicUsize, size: usize) {
52 if size > 1 {
53 scope.spawn(move |scope| divide_and_conquer(scope, counter, size / 2));
54 scope.spawn(move |scope| divide_and_conquer(scope, counter, size / 2));
55 } else {
56 // count the leaves
57 counter.fetch_add(1, Ordering::SeqCst);
58 }
59 }
60
61 fn divide_and_conquer_seq(counter: &AtomicUsize, size: usize) {
62 if size > 1 {
63 divide_and_conquer_seq(counter, size / 2);
64 divide_and_conquer_seq(counter, size / 2);
65 } else {
66 // count the leaves
67 counter.fetch_add(1, Ordering::SeqCst);
68 }
69 }
70
71 struct Tree<T: Send> {
72 value: T,
73 children: Vec<Tree<T>>,
74 }
75
76 impl<T: Send> Tree<T> {
77 fn iter(&self) -> vec::IntoIter<&T> {
78 once(&self.value)
79 .chain(self.children.iter().flat_map(Tree::iter))
80 .collect::<Vec<_>>() // seems like it shouldn't be needed... but prevents overflow
81 .into_iter()
82 }
83
84 fn update<OP>(&mut self, op: OP)
85 where
86 OP: Fn(&mut T) + Sync,
87 T: Send,
88 {
89 scope(|s| self.update_in_scope(&op, s));
90 }
91
92 fn update_in_scope<'scope, OP>(&'scope mut self, op: &'scope OP, scope: &Scope<'scope>)
93 where
94 OP: Fn(&mut T) + Sync,
95 {
96 let Tree {
97 ref mut value,
98 ref mut children,
99 } = *self;
100 scope.spawn(move |scope| {
101 for child in children {
102 scope.spawn(move |scope| child.update_in_scope(op, scope));
103 }
104 });
105
106 op(value);
107 }
108 }
109
110 fn random_tree(depth: usize) -> Tree<u32> {
111 assert!(depth > 0);
112 let mut seed = <XorShiftRng as SeedableRng>::Seed::default();
113 (0..).zip(seed.as_mut()).for_each(|(i, x)| *x = i);
114 let mut rng = XorShiftRng::from_seed(seed);
115 random_tree1(depth, &mut rng)
116 }
117
118 fn random_tree1(depth: usize, rng: &mut XorShiftRng) -> Tree<u32> {
119 let children = if depth == 0 {
120 vec![]
121 } else {
122 (0..rng.random_range(0..4)) // somewhere between 0 and 3 children at each level
123 .map(|_| random_tree1(depth - 1, rng))
124 .collect()
125 };
126
127 Tree {
128 value: rng.random_range(0..1_000_000),
129 children,
130 }
131 }
132
133 #[test]
134 fn update_tree() {
135 let mut tree: Tree<u32> = random_tree(10);
136 let values: Vec<u32> = tree.iter().cloned().collect();
137 tree.update(|v| *v += 1);
138 let new_values: Vec<u32> = tree.iter().cloned().collect();
139 assert_eq!(values.len(), new_values.len());
140 for (&i, &j) in values.iter().zip(&new_values) {
141 assert_eq!(i + 1, j);
142 }
143 }
144
145 /// Check that if you have a chain of scoped tasks where T0 spawns T1
146 /// spawns T2 and so forth down to Tn, the stack space should not grow
147 /// linearly with N. We test this by some unsafe hackery and
148 /// permitting an approx 10% change with a 10x input change.
149 #[test]
150 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
151 fn linear_stack_growth() {
152 let builder = ThreadPoolBuilder::new().num_threads(1);
153 let pool = builder.build().unwrap();
154 pool.install(|| {
155 let mut max_diff = Mutex::new(0);
156 let bottom_of_stack = 0;
157 scope(|s| the_final_countdown(s, &bottom_of_stack, &max_diff, 5));
158 let diff_when_5 = *max_diff.get_mut().unwrap() as f64;
159
160 scope(|s| the_final_countdown(s, &bottom_of_stack, &max_diff, 500));
161 let diff_when_500 = *max_diff.get_mut().unwrap() as f64;
162
163 let ratio = diff_when_5 / diff_when_500;
164 assert!(
165 ratio > 0.9 && ratio < 1.1,
166 "stack usage ratio out of bounds: {ratio}"
167 );
168 });
169 }
170
171 fn the_final_countdown<'scope>(
172 s: &Scope<'scope>,
173 bottom_of_stack: &'scope i32,
174 max: &'scope Mutex<usize>,
175 n: usize,
176 ) {
177 let top_of_stack = 0;
178 let p = bottom_of_stack as *const i32 as usize;
179 let q = &top_of_stack as *const i32 as usize;
180 let diff = p.abs_diff(q);
181
182 let mut data = max.lock().unwrap();
183 *data = Ord::max(diff, *data);
184
185 if n > 0 {
186 s.spawn(move |s| the_final_countdown(s, bottom_of_stack, max, n - 1));
187 }
188 }
189
190 #[test]
191 #[should_panic(expected = "Hello, world!")]
192 fn panic_propagate_scope() {
193 scope(|_| panic!("Hello, world!"));
194 }
195
196 #[test]
197 #[should_panic(expected = "Hello, world!")]
198 fn panic_propagate_spawn() {
199 scope(|s| s.spawn(|_| panic!("Hello, world!")));
200 }
201
202 #[test]
203 #[should_panic(expected = "Hello, world!")]
204 fn panic_propagate_nested_spawn() {
205 scope(|s| s.spawn(|s| s.spawn(|s| s.spawn(|_| panic!("Hello, world!")))));
206 }
207
208 #[test]
209 #[should_panic(expected = "Hello, world!")]
210 fn panic_propagate_nested_scope_spawn() {
211 scope(|s| s.spawn(|_| scope(|s| s.spawn(|_| panic!("Hello, world!")))));
212 }
213
214 #[test]
215 #[cfg_attr(not(panic = "unwind"), ignore)]
216 fn panic_propagate_still_execute_1() {
217 let mut x = false;
218 let result = unwind::halt_unwinding(|| {
219 scope(|s| {
220 s.spawn(|_| panic!("Hello, world!")); // job A
221 s.spawn(|_| x = true); // job B, should still execute even though A panics
222 });
223 });
224 match result {
225 Ok(_) => panic!("failed to propagate panic"),
226 Err(_) => assert!(x, "job b failed to execute"),
227 }
228 }
229
230 #[test]
231 #[cfg_attr(not(panic = "unwind"), ignore)]
232 fn panic_propagate_still_execute_2() {
233 let mut x = false;
234 let result = unwind::halt_unwinding(|| {
235 scope(|s| {
236 s.spawn(|_| x = true); // job B, should still execute even though A panics
237 s.spawn(|_| panic!("Hello, world!")); // job A
238 });
239 });
240 match result {
241 Ok(_) => panic!("failed to propagate panic"),
242 Err(_) => assert!(x, "job b failed to execute"),
243 }
244 }
245
246 #[test]
247 #[cfg_attr(not(panic = "unwind"), ignore)]
248 fn panic_propagate_still_execute_3() {
249 let mut x = false;
250 let result = unwind::halt_unwinding(|| {
251 scope(|s| {
252 s.spawn(|_| x = true); // spawned job should still execute despite later panic
253 panic!("Hello, world!");
254 });
255 });
256 match result {
257 Ok(_) => panic!("failed to propagate panic"),
258 Err(_) => assert!(x, "panic after spawn, spawn failed to execute"),
259 }
260 }
261
262 #[test]
263 #[cfg_attr(not(panic = "unwind"), ignore)]
264 fn panic_propagate_still_execute_4() {
265 let mut x = false;
266 let result = unwind::halt_unwinding(|| {
267 scope(|s| {
268 s.spawn(|_| panic!("Hello, world!"));
269 x = true;
270 });
271 });
272 match result {
273 Ok(_) => panic!("failed to propagate panic"),
274 Err(_) => assert!(x, "panic in spawn tainted scope"),
275 }
276 }
277
278 macro_rules! test_order {
279 ($scope:ident => $spawn:ident) => {{
280 let builder = ThreadPoolBuilder::new().num_threads(1);
281 let pool = builder.build().unwrap();
282 pool.install(|| {
283 let vec = Mutex::new(vec![]);
284 $scope(|scope| {
285 let vec = &vec;
286 for i in 0..10 {
287 scope.$spawn(move |scope| {
288 for j in 0..10 {
289 scope.$spawn(move |_| {
290 vec.lock().unwrap().push(i * 10 + j);
291 });
292 }
293 });
294 }
295 });
296 vec.into_inner().unwrap()
297 })
298 }};
299 }
300
301 #[test]
302 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
303 fn lifo_order() {
304 // In the absence of stealing, `scope()` runs its `spawn()` jobs in LIFO order.
305 let vec = test_order!(scope => spawn);
306 let expected: Vec<i32> = (0..100).rev().collect(); // LIFO -> reversed
307 assert_eq!(vec, expected);
308 }
309
310 #[test]
311 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
312 fn fifo_order() {
313 // In the absence of stealing, `scope_fifo()` runs its `spawn_fifo()` jobs in FIFO order.
314 let vec = test_order!(scope_fifo => spawn_fifo);
315 let expected: Vec<i32> = (0..100).collect(); // FIFO -> natural order
316 assert_eq!(vec, expected);
317 }
318
319 macro_rules! test_nested_order {
320 ($outer_scope:ident => $outer_spawn:ident,
321 $inner_scope:ident => $inner_spawn:ident) => {{
322 let builder = ThreadPoolBuilder::new().num_threads(1);
323 let pool = builder.build().unwrap();
324 pool.install(|| {
325 let vec = Mutex::new(vec![]);
326 $outer_scope(|scope| {
327 let vec = &vec;
328 for i in 0..10 {
329 scope.$outer_spawn(move |_| {
330 $inner_scope(|scope| {
331 for j in 0..10 {
332 scope.$inner_spawn(move |_| {
333 vec.lock().unwrap().push(i * 10 + j);
334 });
335 }
336 });
337 });
338 }
339 });
340 vec.into_inner().unwrap()
341 })
342 }};
343 }
344
345 #[test]
346 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
347 fn nested_lifo_order() {
348 // In the absence of stealing, `scope()` runs its `spawn()` jobs in LIFO order.
349 let vec = test_nested_order!(scope => spawn, scope => spawn);
350 let expected: Vec<i32> = (0..100).rev().collect(); // LIFO -> reversed
351 assert_eq!(vec, expected);
352 }
353
354 #[test]
355 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
356 fn nested_fifo_order() {
357 // In the absence of stealing, `scope_fifo()` runs its `spawn_fifo()` jobs in FIFO order.
358 let vec = test_nested_order!(scope_fifo => spawn_fifo, scope_fifo => spawn_fifo);
359 let expected: Vec<i32> = (0..100).collect(); // FIFO -> natural order
360 assert_eq!(vec, expected);
361 }
362
363 #[test]
364 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
365 fn nested_lifo_fifo_order() {
366 // LIFO on the outside, FIFO on the inside
367 let vec = test_nested_order!(scope => spawn, scope_fifo => spawn_fifo);
368 let expected: Vec<i32> = (0..10)
369 .rev()
370 .flat_map(|i| (0..10).map(move |j| i * 10 + j))
371 .collect();
372 assert_eq!(vec, expected);
373 }
374
375 #[test]
376 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
377 fn nested_fifo_lifo_order() {
378 // FIFO on the outside, LIFO on the inside
379 let vec = test_nested_order!(scope_fifo => spawn_fifo, scope => spawn);
380 let expected: Vec<i32> = (0..10)
381 .flat_map(|i| (0..10).rev().map(move |j| i * 10 + j))
382 .collect();
383 assert_eq!(vec, expected);
384 }
385
386 macro_rules! spawn_push {
387 ($scope:ident . $spawn:ident, $vec:ident, $i:expr) => {{
388 $scope.$spawn(move |_| $vec.lock().unwrap().push($i));
389 }};
390 }
391
392 /// Test spawns pushing a series of numbers, interleaved
393 /// such that negative values are using an inner scope.
394 macro_rules! test_mixed_order {
395 ($outer_scope:ident => $outer_spawn:ident,
396 $inner_scope:ident => $inner_spawn:ident) => {{
397 let builder = ThreadPoolBuilder::new().num_threads(1);
398 let pool = builder.build().unwrap();
399 pool.install(|| {
400 let vec = Mutex::new(vec![]);
401 $outer_scope(|outer_scope| {
402 let vec = &vec;
403 spawn_push!(outer_scope.$outer_spawn, vec, 0);
404 $inner_scope(|inner_scope| {
405 spawn_push!(inner_scope.$inner_spawn, vec, -1);
406 spawn_push!(outer_scope.$outer_spawn, vec, 1);
407 spawn_push!(inner_scope.$inner_spawn, vec, -2);
408 spawn_push!(outer_scope.$outer_spawn, vec, 2);
409 spawn_push!(inner_scope.$inner_spawn, vec, -3);
410 });
411 spawn_push!(outer_scope.$outer_spawn, vec, 3);
412 });
413 vec.into_inner().unwrap()
414 })
415 }};
416 }
417
418 #[test]
419 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
420 fn mixed_lifo_order() {
421 // NB: the end of the inner scope makes us execute some of the outer scope
422 // before they've all been spawned, so they're not perfectly LIFO.
423 let vec = test_mixed_order!(scope => spawn, scope => spawn);
424 let expected = vec![-3, 2, -2, 1, -1, 3, 0];
425 assert_eq!(vec, expected);
426 }
427
428 #[test]
429 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
430 fn mixed_fifo_order() {
431 let vec = test_mixed_order!(scope_fifo => spawn_fifo, scope_fifo => spawn_fifo);
432 let expected = vec![-1, 0, -2, 1, -3, 2, 3];
433 assert_eq!(vec, expected);
434 }
435
436 #[test]
437 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
438 fn mixed_lifo_fifo_order() {
439 // NB: the end of the inner scope makes us execute some of the outer scope
440 // before they've all been spawned, so they're not perfectly LIFO.
441 let vec = test_mixed_order!(scope => spawn, scope_fifo => spawn_fifo);
442 let expected = vec![-1, 2, -2, 1, -3, 3, 0];
443 assert_eq!(vec, expected);
444 }
445
446 #[test]
447 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
448 fn mixed_fifo_lifo_order() {
449 let vec = test_mixed_order!(scope_fifo => spawn_fifo, scope => spawn);
450 let expected = vec![-3, 0, -2, 1, -1, 2, 3];
451 assert_eq!(vec, expected);
452 }
453
454 #[test]
455 fn static_scope() {
456 static COUNTER: AtomicUsize = AtomicUsize::new(0);
457
458 let mut range = 0..100;
459 let sum = range.clone().sum();
460 let iter = &mut range;
461
462 COUNTER.store(0, Ordering::Relaxed);
463 scope(|s: &Scope<'static>| {
464 // While we're allowed the locally borrowed iterator,
465 // the spawns must be static.
466 for i in iter {
467 s.spawn(move |_| {
468 COUNTER.fetch_add(i, Ordering::Relaxed);
469 });
470 }
471 });
472
473 assert_eq!(COUNTER.load(Ordering::Relaxed), sum);
474 }
475
476 #[test]
477 fn static_scope_fifo() {
478 static COUNTER: AtomicUsize = AtomicUsize::new(0);
479
480 let mut range = 0..100;
481 let sum = range.clone().sum();
482 let iter = &mut range;
483
484 COUNTER.store(0, Ordering::Relaxed);
485 scope_fifo(|s: &ScopeFifo<'static>| {
486 // While we're allowed the locally borrowed iterator,
487 // the spawns must be static.
488 for i in iter {
489 s.spawn_fifo(move |_| {
490 COUNTER.fetch_add(i, Ordering::Relaxed);
491 });
492 }
493 });
494
495 assert_eq!(COUNTER.load(Ordering::Relaxed), sum);
496 }
497
498 #[test]
499 fn mixed_lifetime_scope() {
500 fn increment<'slice, 'counter>(counters: &'slice [&'counter AtomicUsize]) {
501 scope(move |s: &Scope<'counter>| {
502 // We can borrow 'slice here, but the spawns can only borrow 'counter.
503 for &c in counters {
504 s.spawn(move |_| {
505 c.fetch_add(1, Ordering::Relaxed);
506 });
507 }
508 });
509 }
510
511 let counter = AtomicUsize::new(0);
512 increment(&[&counter; 100]);
513 assert_eq!(counter.into_inner(), 100);
514 }
515
516 #[test]
517 fn mixed_lifetime_scope_fifo() {
518 fn increment<'slice, 'counter>(counters: &'slice [&'counter AtomicUsize]) {
519 scope_fifo(move |s: &ScopeFifo<'counter>| {
520 // We can borrow 'slice here, but the spawns can only borrow 'counter.
521 for &c in counters {
522 s.spawn_fifo(move |_| {
523 c.fetch_add(1, Ordering::Relaxed);
524 });
525 }
526 });
527 }
528
529 let counter = AtomicUsize::new(0);
530 increment(&[&counter; 100]);
531 assert_eq!(counter.into_inner(), 100);
532 }
533
534 #[test]
535 fn scope_spawn_broadcast() {
536 let sum = AtomicUsize::new(0);
537 let n = scope(|s| {
538 s.spawn_broadcast(|_, ctx| {
539 sum.fetch_add(ctx.index(), Ordering::Relaxed);
540 });
541 crate::current_num_threads()
542 });
543 assert_eq!(sum.into_inner(), n * (n - 1) / 2);
544 }
545
546 #[test]
547 fn scope_fifo_spawn_broadcast() {
548 let sum = AtomicUsize::new(0);
549 let n = scope_fifo(|s| {
550 s.spawn_broadcast(|_, ctx| {
551 sum.fetch_add(ctx.index(), Ordering::Relaxed);
552 });
553 crate::current_num_threads()
554 });
555 assert_eq!(sum.into_inner(), n * (n - 1) / 2);
556 }
557
558 #[test]
559 fn scope_spawn_broadcast_nested() {
560 let sum = AtomicUsize::new(0);
561 let n = scope(|s| {
562 s.spawn_broadcast(|s, _| {
563 s.spawn_broadcast(|_, ctx| {
564 sum.fetch_add(ctx.index(), Ordering::Relaxed);
565 });
566 });
567 crate::current_num_threads()
568 });
569 assert_eq!(sum.into_inner(), n * n * (n - 1) / 2);
570 }
571
572 #[test]
573 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
574 fn scope_spawn_broadcast_barrier() {
575 let barrier = Barrier::new(8);
576 let pool = ThreadPoolBuilder::new().num_threads(7).build().unwrap();
577 pool.in_place_scope(|s| {
578 s.spawn_broadcast(|_, _| {
579 barrier.wait();
580 });
581 barrier.wait();
582 });
583 }
584
585 #[test]
586 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
587 fn scope_spawn_broadcast_panic_one() {
588 let count = AtomicUsize::new(0);
589 let pool = ThreadPoolBuilder::new().num_threads(7).build().unwrap();
590 let result = crate::unwind::halt_unwinding(|| {
591 pool.scope(|s| {
592 s.spawn_broadcast(|_, ctx| {
593 count.fetch_add(1, Ordering::Relaxed);
594 if ctx.index() == 3 {
595 panic!("Hello, world!");
596 }
597 });
598 });
599 });
600 assert_eq!(count.into_inner(), 7);
601 assert!(result.is_err(), "broadcast panic should propagate!");
602 }
603
604 #[test]
605 #[cfg_attr(any(target_os = "emscripten", target_family = "wasm"), ignore)]
606 fn scope_spawn_broadcast_panic_many() {
607 let count = AtomicUsize::new(0);
608 let pool = ThreadPoolBuilder::new().num_threads(7).build().unwrap();
609 let result = crate::unwind::halt_unwinding(|| {
610 pool.scope(|s| {
611 s.spawn_broadcast(|_, ctx| {
612 count.fetch_add(1, Ordering::Relaxed);
613 if ctx.index() % 2 == 0 {
614 panic!("Hello, world!");
615 }
616 });
617 });
618 });
619 assert_eq!(count.into_inner(), 7);
620 assert!(result.is_err(), "broadcast panic should propagate!");
621 }