1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- use std::{sync::mpsc, thread, time::Duration};
- /// 单个生产者
- #[test]
- fn test_sigle_std_mpsc_channel() {
- let (tx, rx) = mpsc::channel();
- thread::spawn(move || {
- let vals = vec![
- String::from("hi"),
- String::from("from"),
- String::from("the"),
- String::from("thread"),
- ];
- for val in vals {
- tx.send(val).unwrap();
- thread::sleep(Duration::from_secs(1));
- }
- });
- for received in rx {
- println!("Got: {}", received);
- }
- }
- /// 多个生产者
- #[test]
- fn test_mult_std_mpsc_channel() {
- let (tx, rx) = mpsc::channel();
- let tx1 = tx.clone();
- thread::spawn(move || {
- let vals = vec![
- String::from("hi"),
- String::from("from"),
- String::from("the"),
- String::from("thread"),
- ];
- for val in vals {
- tx1.send(val).unwrap();
- thread::sleep(Duration::from_secs(1));
- }
- });
- thread::spawn(move || {
- let vals = vec![
- String::from("more"),
- String::from("messages"),
- String::from("for"),
- String::from("you"),
- ];
- for val in vals {
- tx.send(val).unwrap();
- thread::sleep(Duration::from_secs(1));
- }
- });
- for received in rx {
- println!("Got: {received}");
- }
- }
|