Created
September 23, 2020 23:33
-
-
Save jcbritobr/7a516a28681cd6ec6c2cf9f857166f56 to your computer and use it in GitHub Desktop.
SPCMC(Single Producer, Multiple Consumer) pattern in Rust
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, sync::Arc, sync::Mutex, thread}; | |
type Closure = Box<dyn FnOnce() + Send + 'static>; | |
const ERR_LOCK: &str = "cant acquire resource"; | |
fn main() { | |
let (tx, rx) = mpsc::channel::<Closure>(); | |
let rxtf = Arc::new(Mutex::new(rx)); | |
let rx1 = Arc::clone(&rxtf); | |
let rx2 = Arc::clone(&rxtf); | |
let handle = thread::spawn(move || loop { | |
let data = match rx1.lock().expect(ERR_LOCK).recv() { | |
Ok(data) => data, | |
Err(_) => break, | |
}; | |
data(); | |
}); | |
let handle2 = thread::spawn(move || loop { | |
let data = match rx2.lock().expect(ERR_LOCK).recv() { | |
Ok(data) => data, | |
Err(_) => break, | |
}; | |
data(); | |
}); | |
for i in 0..100000 { | |
tx.send(Box::new(move || { | |
println!("data:{}", i); | |
})) | |
.unwrap(); | |
} | |
drop(tx); | |
handle.join().expect("cant merge thread"); | |
handle2.join().expect("cant merge thread"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment