10 stable releases

3.3.1 Sep 25, 2023
3.3.0 Apr 7, 2023
3.2.0 Dec 30, 2021
3.1.0 Jul 22, 2020
1.0.1 May 26, 2020

#270 in Concurrency

Download history 2001/week @ 2024-03-14 2952/week @ 2024-03-21 2575/week @ 2024-03-28 2040/week @ 2024-04-04 2359/week @ 2024-04-11 2441/week @ 2024-04-18 2193/week @ 2024-04-25 2069/week @ 2024-05-02 1954/week @ 2024-05-09 1862/week @ 2024-05-16 1941/week @ 2024-05-23 2220/week @ 2024-05-30 1672/week @ 2024-06-06 2366/week @ 2024-06-13 2248/week @ 2024-06-20 1343/week @ 2024-06-27

7,901 downloads per month
Used in 45 crates (26 directly)

Apache-2.0 OR MIT

13KB
116 lines

easy-parallel

Build License Cargo Documentation

Run closures in parallel.

This is a simple primitive for spawning threads in bulk and waiting for them to complete. Threads are allowed to borrow local variables from the main thread.

Examples

Run two threads that increment a number:

use easy_parallel::Parallel;
use std::sync::Mutex;

let mut m = Mutex::new(0);

Parallel::new()
    .add(|| *m.lock().unwrap() += 1)
    .add(|| *m.lock().unwrap() += 1)
    .run();

assert_eq!(*m.get_mut().unwrap(), 2);

Square each number of a vector on a different thread:

use easy_parallel::Parallel;

let v = vec![10, 20, 30];

let squares = Parallel::new()
    .each(0..v.len(), |i| v[i] * v[i])
    .run();

assert_eq!(squares, [100, 400, 900]);

Compute the sum of numbers in an array:

use easy_parallel::Parallel;

fn par_sum(v: &[i32]) -> i32 {
    const THRESHOLD: usize = 2;

    if v.len() <= THRESHOLD {
        v.iter().copied().sum()
    } else {
        let half = (v.len() + 1) / 2;
        let sums = Parallel::new().each(v.chunks(half), par_sum).run();
        sums.into_iter().sum()
    }
}

let v = [1, 25, -4, 10, 8];
assert_eq!(par_sum(&v), 40);

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps