Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Rust

Idiom #30 Parallelize execution of 1000 independent tasks

Launch the concurrent execution of the procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.

extern crate rayon;
use rayon::prelude::*;
(0..1000).into_par_iter().for_each(f);

Requires the rayon crate.
(https://crates.io/crates/rayon)
use std::thread;
let threads: Vec<_> = (0..1000).map(|i| {
	thread::spawn(move || f(i))
}).collect();

for thread in threads {
	thread.join();
}

If you don't join the threads, the program will just exit and the threads will be killed.

This would be better implemented with a thread pool but the standard library doesn't include one.
(dorun (pmap f (range 1 1001)))

New implementation...