pub fn scope<'env, F, R>(body: F) -> RExpand description
Create a borrowing scope for parallel sub-tasks.
Within the body closure, Scope::spawn registers jobs on the unified
scheduler. The scope blocks until every spawned job has completed before
returning, so tasks may borrow non-'static data from the enclosing
environment.
This is the Rayon-style scope shape, adapted to Moirai’s unified hybrid
scheduler.
§Examples
use moirai_parallel::scope;
let data: Vec<u64> = (0..1000).collect();
use std::sync::atomic::{AtomicU64, Ordering};
let sum = AtomicU64::new(0);
scope(|s| {
s.spawn(|| {
sum.fetch_add(data.iter().sum::<u64>(), Ordering::Relaxed);
});
s.spawn(|| {
sum.fetch_add(data.len() as u64, Ordering::Relaxed);
});
});
assert_eq!(sum.load(Ordering::Relaxed), data.iter().sum::<u64>() + 1000);A task cannot borrow a value local to the body, which is dropped before the scheduler runs the buffered task:
ⓘ
moirai_parallel::scope(|s| {
let local = vec![7_u8; 8];
let borrowed = &local;
s.spawn(move || assert_eq!(borrowed[0], 7));
});