Skip to content

Instantly share code, notes, and snippets.

Created August 14, 2015 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/00778b17c01a5ee00963 to your computer and use it in GitHub Desktop.
Save anonymous/00778b17c01a5ee00963 to your computer and use it in GitHub Desktop.
// This is a rather inefficient version of a function that executes a closure on two arguments, concurrently.
// We need an iterator that yields two owned elements, and we'd like to avoid heap allocation.
mod both {
struct TwoElements<T> {
el1: Option<T>,
el2: Option<T>,
}
impl<T> TwoElements<T> {
fn new(x: T, y: T) -> Self {
TwoElements { el1: Some(x), el2: Some(y) }
}
fn iter(&mut self) -> Iter<T> {
Iter { elems: self }
}
}
struct Iter<'a, T> where T: 'a {
elems: &'a mut TwoElements<T>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let el = self.elems.el1.take();
if let Some(x) = el {
Some(x)
}
else {
self.elems.el2.take()
}
}
}
pub fn both<T, F>(x: T, y: T, f: F)
where T: Send,
F: Sync + Fn(T)
{
use simple_parallel::Pool;
let mut pool = Pool::new(2);
pool.for_(TwoElements::new(x, y).iter(), f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment