Skip to content

Instantly share code, notes, and snippets.

@cedelmaier
Created June 14, 2015 17:51
Show Gist options
  • Save cedelmaier/75ca1c81fee550f32d76 to your computer and use it in GitHub Desktop.
Save cedelmaier/75ca1c81fee550f32d76 to your computer and use it in GitHub Desktop.
comm_simple
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());
}
}
@cedelmaier
Copy link
Author

Cargo.toml needs [dependencies] rand = "*" and [dependencies.comm] git = "https://github.com/mahkoh/comm"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment