Skip to main content

ParallelRun

Trait ParallelRun 

Source
pub trait ParallelRun {
    type Output: Send + 'static;

    // Required method
    fn par_run(self) -> Result<Vec<Self::Output>>;
}
Expand description

An extension trait that provides a method to run multiple Runnable’s in parallel.

This trait is automatically implemented for any Vec<T> where T implements Runnable. You do not need to implement this trait manually.

The parallel execution is optimized to use the number of available CPU cores, dividing the tasks into chunks and processing them concurrently.

Required Associated Types§

Source

type Output: Send + 'static

Required Methods§

Source

fn par_run(self) -> Result<Vec<Self::Output>>

Spawns multiple threads to execute the run method of each task in parallel.

The number of threads spawned is determined by the number of available CPU cores, with tasks divided evenly among them. Each thread processes a chunk of tasks sequentially, while chunks are processed in parallel.

§Returns

Returns a std::thread::Result<Vec<Self::Output>> containing the results of each task, in the same order as the input vector. Returns an error if any thread panics.

§Examples
use struct_threads::{Runnable, ParallelRun};

struct MathTask(i32, i32);

impl Runnable for MathTask {
   type Output = i32;

  fn run(self) -> Self::Output {
      self.0 + self.1
  }
}

let tasks = vec![MathTask(1, 2), MathTask(3, 4), MathTask(5, 6)];

let results = tasks
    .par_run()
    .unwrap(); // Provided by the ParallelRun trait
assert_eq!(results, vec![3, 7, 11]);

Implementations on Foreign Types§

Source§

impl<T: Runnable> ParallelRun for Vec<T>

Source§

type Output = <T as Runnable>::Output

Source§

fn par_run(self) -> Result<Vec<Self::Output>>

Implementors§