Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. use std::sync::mpsc;
  2.  
  3. fn main() {
  4. let mut handles = vec![];
  5. let (sender, receiver) = mpsc::channel();
  6. for i in 0..10 {
  7. let sender_clone = sender.clone();
  8. // move block says the thread now owns this cloned sender end of the channel.
  9. // once the thread scope ends, this sender clone will be dropped
  10. handles.push(std::thread::spawn(move ||
  11. sender_clone.send(i)))
  12. }
  13. // drop the original sender; that way once all sender threads are dropped
  14. // the channel will close
  15. drop(sender);
  16.  
  17. // iterate over all entries coming from the channel
  18. for x in receiver.iter() {
  19. println!("Got {}", x);
  20. }
  21.  
  22. // join the threads
  23. for handle in handles {
  24. let _ = handle.join().unwrap();
  25. }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement