Created
June 14, 2015 17:51
-
-
Save cedelmaier/75ca1c81fee550f32d76 to your computer and use it in GitHub Desktop.
comm_simple
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
extern crate comm; | |
extern crate rand; | |
use std::{thread}; | |
use comm::{spmc}; | |
use rand::{Rng}; | |
fn main() { | |
let (send, recv) = spmc::unbounded::new(); | |
// Start the listeners | |
// Use a JoinHandle to collect the threads | |
// Then start listening, which is a blocking | |
// operation. | |
let recv_guards: Vec<_> = (0..3).map( |i| { | |
let recv = recv.clone(); | |
thread::spawn(move || { | |
// Loop forever until the channel | |
// is disconnected | |
let mut rng = rand::thread_rng(); | |
while let Ok(n) = recv.recv_sync() { | |
// Simulate work! | |
thread::sleep_ms((1000.0 * rng.gen::<f32>()) as u32); | |
println!("\tRecv:{} processed {}", i, n); | |
} | |
}) | |
}).collect(); | |
// Start the sender | |
// Use a JoinHandle to explicitly join | |
// at the end of the program | |
let send_guard = thread::spawn(move || { | |
for i in 0..10 { | |
send.send(i).unwrap(); | |
println!("Sent: {}", i); | |
} | |
}); | |
println!("{:?}", send_guard.join().unwrap()); | |
for i in recv_guards { | |
println!("{:?}", i.join().unwrap()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cargo.toml needs [dependencies] rand = "*" and [dependencies.comm] git = "https://github.com/mahkoh/comm"