pub trait TokioParallelRun {
type Output: Send + 'static;
// Required method
fn async_par_run(
self,
) -> impl Future<Output = Result<Vec<Self::Output>, JoinError>> + Send;
}Available on crate feature
tokio only.Expand description
An extension trait that provides a method to run multiple AsyncRunnable’s in parallel using Tokio.
This trait is automatically implemented for any Vec<T> where T implements AsyncRunnable
when the tokio feature is enabled. You do not need to implement this trait manually.
§Examples
use struct_threads::{AsyncRunnable, TokioParallelRun};
struct AsyncMathTask(i32, i32);
impl AsyncRunnable for AsyncMathTask {
type Output = i32;
fn run(self) -> impl std::future::Future<Output = Self::Output> + Send {
async move {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
self.0 + self.1
}
}
}
#[tokio::main]
async fn main() {
let tasks = vec![
AsyncMathTask(1, 2),
AsyncMathTask(3, 4),
AsyncMathTask(5, 6)
];
let results = tasks.async_par_run().await.unwrap();
assert_eq!(results, vec![3, 7, 11]);
}Required Associated Types§
Required Methods§
Sourcefn async_par_run(
self,
) -> impl Future<Output = Result<Vec<Self::Output>, JoinError>> + Send
fn async_par_run( self, ) -> impl Future<Output = Result<Vec<Self::Output>, JoinError>> + Send
Spawns multiple Tokio tasks to execute the run method of each task in parallel.
All tasks are spawned concurrently and their results are collected in the same order as the input vector.
§Returns
Returns a future that resolves to Result<Vec<Self::Output>, tokio::task::JoinError>
containing the results of each task, or a join error if any task panics.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.