Function lattice_qcd_rs::thread::run_pool_parallel
source · pub fn run_pool_parallel<Key, Data, CommonData, F>(
iter: impl Iterator<Item = Key> + Send,
common_data: &CommonData,
closure: &F,
number_of_thread: usize,
capacity: usize
) -> Result<HashMap<Key, Data>, ThreadAnyError>where
CommonData: Sync,
Key: Eq + Hash + Send + Clone + Sync,
Data: Send,
F: Sync + Clone + Fn(&Key, &CommonData) -> Data,
Expand description
run jobs in parallel.
The pool of job is given by iter
. the job is given by closure
that have the form |key,common_data| -> Data
.
number_of_thread
determine the number of job done in parallel and should be greater than 0,
otherwise return ThreadAnyError::ThreadNumberIncorrect
.
capacity
is used to determine the capacity of the HashMap
upon initiation (see HashMap::with_capacity
)
Errors
Returns ThreadAnyError::ThreadNumberIncorrect
is the number of threads is 0.
Returns ThreadAnyError::Panic
if a thread panicked. Contains the panic message.
Example
let us computes the value of i^2 * c
for i in [2,9999] with 4 threads
let iter = 2..10000;
let c = 5;
// we could have put 4 inside the closure but this demonstrate how to use common data
let result = run_pool_parallel(iter, &c, &|i, c| i * i * c, 4, 10000 - 2)?;
assert_eq!(*result.get(&40).unwrap(), 40 * 40 * c);
assert_eq!(result.get(&1), None);
In the next example a thread will panic, we demonstrate the return type.
ⓘ
let iter = 0..10;
let result = run_pool_parallel(iter, &(), &|_, _| panic!("{}", "panic message"), 4, 10);
match result {
Ok(_) => {}
Err(err) => panic!("{}", err),
}
This give the following panic message
stderr:
thread '<unnamed>' panicked at 'panic message', src\thread.rs:6:51
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread '<unnamed>' panicked at 'panic message', src\thread.rs:6:51
thread '<unnamed>' panicked at 'panic message', src\thread.rs:6:51
thread '<unnamed>' panicked at 'panic message', src\thread.rs:6:51
thread 'main' panicked at '4 threads panicked with ["panic message" ,"panic message" ,"panic message" ,"panic message"]', src\thread.rs:9:17