std_mpsc_channel.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use std::{sync::mpsc, thread, time::Duration};
  2. /// 单个生产者
  3. #[test]
  4. fn test_sigle_std_mpsc_channel() {
  5. let (tx, rx) = mpsc::channel();
  6. thread::spawn(move || {
  7. let vals = vec![
  8. String::from("hi"),
  9. String::from("from"),
  10. String::from("the"),
  11. String::from("thread"),
  12. ];
  13. for val in vals {
  14. tx.send(val).unwrap();
  15. thread::sleep(Duration::from_secs(1));
  16. }
  17. });
  18. for received in rx {
  19. println!("Got: {}", received);
  20. }
  21. }
  22. /// 多个生产者
  23. #[test]
  24. fn test_mult_std_mpsc_channel() {
  25. let (tx, rx) = mpsc::channel();
  26. let tx1 = tx.clone();
  27. thread::spawn(move || {
  28. let vals = vec![
  29. String::from("hi"),
  30. String::from("from"),
  31. String::from("the"),
  32. String::from("thread"),
  33. ];
  34. for val in vals {
  35. tx1.send(val).unwrap();
  36. thread::sleep(Duration::from_secs(1));
  37. }
  38. });
  39. thread::spawn(move || {
  40. let vals = vec![
  41. String::from("more"),
  42. String::from("messages"),
  43. String::from("for"),
  44. String::from("you"),
  45. ];
  46. for val in vals {
  47. tx.send(val).unwrap();
  48. thread::sleep(Duration::from_secs(1));
  49. }
  50. });
  51. for received in rx {
  52. println!("Got: {received}");
  53. }
  54. }