Two threads sending messages



examples/threads/threads-messages-multiple-sources/src/main.rs
use std::sync::mpsc;
use std::thread;
use std::time::Duration;


fn main() {
    let (tx1, rx) = mpsc::channel();
    let tx2 = tx1.clone();

    println!("{:?}: start", thread::current().id());

    thread::spawn(move || {
        for i in 1..=5 {
            thread::sleep(Duration::from_millis(1));
            tx1.send(format!("{:?}: {}", thread::current().id(), i)).unwrap();
        }
        println!("Spawned thread {:?} ends", thread::current().id());
    });

    thread::spawn(move || {
        for i in 1..=5 {
            thread::sleep(Duration::from_millis(1));
            tx2.send(format!("{:?}: {}", thread::current().id(), i)).unwrap();
        }
        println!("Spawned thread {:?} ends", thread::current().id());
    });

    for received in rx {
        println!("Got: {}", received);
    }

    println!("Main thread ends");
}

ThreadId(1): start
Got: ThreadId(2): 1
Got: ThreadId(3): 1
Got: ThreadId(3): 2
Got: ThreadId(2): 2
Got: ThreadId(3): 3
Got: ThreadId(2): 3
Got: ThreadId(2): 4
Got: ThreadId(3): 4
Spawned thread ThreadId(2) ends
Spawned thread ThreadId(3) ends
Got: ThreadId(2): 5
Got: ThreadId(3): 5
Main thread ends