Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Forked from rust-play/playground.rs
Last active July 12, 2018 19:08
Show Gist options
  • Save piboistudios/6a6cb5d277300cc0df957fb6569eb9a1 to your computer and use it in GitHub Desktop.
Save piboistudios/6a6cb5d277300cc0df957fb6569eb9a1 to your computer and use it in GitHub Desktop.
[RUST]Channels (#5)
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
fn main() {
// start by creating a channel
let (tx, rx) = mpsc::channel();
// we need to create a clone of the transmitter because each thread actually
// owns the copy we give it... and it's greedy so it won't give it back :(
let tx1 = mpsc::Sender::clone(&tx);
thread::spawn(move || { // we lose tx1 in the outer scope here with the 'move' keyword
for _ in 0..10 { // send messages 10 times
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
// send each value in the vector above to our receiver
for val in vals {
tx1.send(val).unwrap();
thread::sleep(Duration::from_millis(500));
}
}
});
thread::spawn(move || { //we lose tx in the outer scope here with the 'move' keyword
for _ in 0..10 { // send different messages 10 times
let vals = vec![
String::from("bye"),
String::from("from yet"),
String::from("another"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_millis(500));
}
}
});
// this is the part i love about channels....
for received in rx {
// this. code. blocks. until. a. message. is. received...
println!("Got: {}", received);
} // this loop exits when both threads are closed because...
// the implementation of channels in Rust dictates that a channel is closed if:
// all references to transmitters are dropped
// the reference to the receiver is dropped
println!("Done");
}
// that last bit was a lot, basically iterating over the channel receiver blocks until
// the next value exists
// so basically this loop blocks as long as there are transmitters and receivers
// this program runs as long as you can send/receive more values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment