Created
January 22, 2017 11:44
-
-
Save thibran/b441e6fab4395b5656f7c7016d1c85b6 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
use std::sync::mpsc::{self, Sender, Receiver}; | |
use std::sync::{Arc, Mutex}; | |
#[derive(Clone, Debug)] | |
pub struct Spmc<T> { | |
pub tx: Sender<T>, | |
pub rx: Reader<T>, | |
} | |
impl<T> Spmc<T> { | |
pub fn new() -> Spmc<T> { | |
let (tx, rx) = Reader::channel(); | |
Spmc { tx: tx, rx: rx } | |
} | |
} | |
#[derive(Clone, Debug)] | |
pub struct Reader<T> { | |
c: Arc<Mutex<Receiver<T>>>, | |
} | |
impl<T> Reader<T> { | |
fn channel() -> (Sender<T>, Reader<T>) { | |
let (tx, rx) = mpsc::channel(); | |
(tx, Reader { c: Arc::new(Mutex::new(rx)) }) | |
} | |
} | |
impl<T> Iterator for Reader<T> { | |
type Item = T; | |
fn next(&mut self) -> Option<T> { | |
self.c.lock().ok().and_then(|c| c.recv().ok()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment