Skip to content

Instantly share code, notes, and snippets.

@thibran
Created January 22, 2017 11:44
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 thibran/b441e6fab4395b5656f7c7016d1c85b6 to your computer and use it in GitHub Desktop.
Save thibran/b441e6fab4395b5656f7c7016d1c85b6 to your computer and use it in GitHub Desktop.
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