Rust多线程中的消息传递机制

代码说话。

use std::thread;
use std::sync::mpsc;
use std::time::Duration;

fn main() {

    let (tx, rx) = mpsc::channel();
    let tx1 = mpsc::Sender::clone(&tx);

    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("from"),
            String::from("you"),
        ];
        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

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

Rust多线程中的消息传递机制_第1张图片

转载于:https://www.cnblogs.com/aguncn/p/11441608.html

你可能感兴趣的:(Rust多线程中的消息传递机制)