Skip to content

Instantly share code, notes, and snippets.

@ales-tsurko
Last active October 19, 2021 10:19
Show Gist options
  • Save ales-tsurko/39d39fdf9f033fe6be63d7accf4e5360 to your computer and use it in GitHub Desktop.
Save ales-tsurko/39d39fdf9f033fe6be63d7accf4e5360 to your computer and use it in GitHub Desktop.
use std::sync::Arc;
use std::thread;
const THRESHOLD: usize = 1000;
fn main() {
let input: Vec<u64> = (0..2000).collect();
let result = splitter(input.clone(), |v| v * 2);
assert_eq!(
result,
input.into_iter().map(|v| v * 2).collect::<Vec<u64>>()
);
}
fn splitter<T, R, F>(values: Vec<T>, handler: F) -> Vec<R>
where
T: Clone + Send + 'static,
R: Send + 'static,
F: (Fn(T) -> R) + Send + Sync + 'static,
{
if values.len() < THRESHOLD {
return values.into_iter().map(handler).collect();
}
let input = values[THRESHOLD..].to_owned();
let handler = Arc::new(handler);
let join_handle = {
let handler = Arc::clone(&handler);
thread::spawn(move || input.into_iter().map(|v| handler(v)).collect::<Vec<R>>())
};
let mut result: Vec<R> = values[..THRESHOLD]
.into_iter()
.cloned()
.map(|v| handler(v))
.collect();
result.append(&mut join_handle.join().unwrap());
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment