pub async fn scope<'scope, F, O>(f: F) -> Vec<Result<O, JoinError>>Expand description
Async scope helper
This function helps you write unsafe asynchronous structured concurrent code more easily. but it is still unsafe, so need to be careful when using it.
To use it safely,
the user needs to ensure that the task is done within used reference lifetime.
Due to std::mem::forget, the Rust currently cannot guarantee it.
From a practical point of view, the following points need to be note
.awaitas early as possible- Don’t put task into container unless you know what you are doing
- Don’t call
std::mem::forget
§Example
let list: Vec<u32> = vec![1, 2, 3, 4];
rspack_parallel::scope(|token| {
for i in 0..list.len() {
let s = unsafe { token.used(&list) };
s.spawn(move |list| async move {
&list[i];
});
}
})
.await;This doesn’t compile
ⓘ
rspack_parallel::scope(|token| {
let list: Vec<u32> = vec![1, 2, 3, 4];
for i in 0..list.len() {
let s = unsafe { token.used(&list) };
s.spawn(move |list| async move {
&list[i];
});
}
})
.await;