Rust 编程视频教程(进阶)——017_3 消息传递 3

视频地址

头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rus...

讲解内容

多个生产者例子:

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

fn main() {
    let (tx, rx) = mpsc::channel();
    let tx1 = mpsc::Sender::clone(&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("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);
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
119
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商