-
-
Save urschrei/b4636b549bfec59afcef to your computer and use it in GitHub Desktop.
Threaded send/receive using channels in Rust
This file contains hidden or 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::thread; | |
use std::sync::mpsc::{ channel, Sender }; | |
enum Wrapped { | |
A(f64), | |
B(f64), | |
} | |
fn produce_a(sender: Sender<Wrapped>) { | |
for i in 0 .. 5 { | |
sender.send( Wrapped::A(i as f64) ).unwrap(); | |
} | |
} | |
fn produce_b(sender: Sender<Wrapped>) { | |
for i in 0 .. 8 { | |
sender.send( Wrapped::B(i as f64) ).unwrap(); | |
} | |
} | |
fn main() { | |
let (tx, rx) = channel(); | |
let tx2 = tx.clone(); | |
thread::spawn(move || produce_a(tx)); | |
thread::spawn(move || produce_b(tx2)); | |
let mut total_a = 0.0; | |
let mut total_b = 0.0; | |
loop { | |
match rx.recv() { | |
Ok(Wrapped::A(a)) => total_a += a, | |
Ok(Wrapped::B(b)) => total_b += b, | |
Err(_) => break, | |
} | |
} | |
println!("Result - a: {}, b: {}", total_a, total_b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment