Created
August 14, 2015 17:47
-
-
Save anonymous/00778b17c01a5ee00963 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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