Function mth_calc::run_on_all_cpus[][src]

pub fn run_on_all_cpus<T: Send + 'static>(
    body: fn() -> T,
    initial: T,
    agg: fn(_: T, _: T) -> T
) -> (T, u32)

Runs a given closure in parallel on all available CPUs.

The given closure can return a value. All return values of all closure executions are aggregated with a given aggregation closure. The method returns a tuple with the aggregated result and the number of executions (=number of CPUs).

Arguments

  • body - closure that should be run in parallel on all available processors.
  • initial - initial value used for aggregating the results of all closure executions.
  • agg - closure used to aggregate method results.

Examples

use mth_calc::run_on_all_cpus;
use rand::prelude::*;
 
let result = mth_calc::run_on_all_cpus::<f32>(|| {
    // Create a thread-local random generator
    let mut rng = thread_rng();

    // Calculate sum over ten random numbers
    let mut total = 0f32;
    for _ in 0..10 {
        total += rng.gen::<f32>();
    }

    total
}, 
0f32, // initial value for aggreation is zero
|x, y| { x + y }); // aggregation function = sum
 
let avg = result.0 / (result.1 * 10) as f32;
println!("The average random number was {}", avg);