Skip to content

Instantly share code, notes, and snippets.

@sheepla
Created July 25, 2024 11:50
Show Gist options
  • Save sheepla/c042c902d0b52f64c185e83ddef172f7 to your computer and use it in GitHub Desktop.
Save sheepla/c042c902d0b52f64c185e83ddef172f7 to your computer and use it in GitHub Desktop.
mpsc::channel example
use std::sync::mpsc;
use std::thread;
fn main() {
let (sender1, recceiver) = mpsc::channel();
let sender2 = mpsc::Sender::clone(&sender1);
let _ = thread::spawn(move || {
let data = vec!["One".to_string(), "Two".to_string(), "Three".to_string(), "Four".to_string()];
for n in data {
sender1.send(n).unwrap();
}
});
let _ = thread::spawn(move || {
let data = vec!["Five".to_string(), "Six".to_string(), "Seven".to_string(), "Eight".to_string()];
for n in data {
sender2.send(n).unwrap();
}
});
for receied in recceiver {
println!("Received: {}", receied);
}
}
@sheepla
Copy link
Author

sheepla commented Jul 25, 2024

$ cargo run
 Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/channel`
Received: One
Received: Five
Received: Two
Received: Three
Received: Four
Received: Six
Received: Seven
Received: Eight

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