Dzwebs.Net

撰写电脑技术杂文十余年

rust多线程利用通道mpsc(channel)实现多发送单接收的示例

Admin | 2023-12-4 20:17:00 | 被阅次数 | 806

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

    在RUST语言中,可以通过std::threadg构造多线程,并通过td::sync::mpsc实现通道中的多发送及单接收的功能。

use std::sync::mpsc;

use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::channel();
let mut haddles =vec![];
for i in 1..11{
let m = i.clone();
let tx1 = tx.clone();
let haddle = thread::spawn(move || {
tx1.send(format!("the number is {}",m)).unwrap();
});
haddles.push(haddle);
}
for h in haddles{
h.join().unwrap();
}
drop(tx);
// while let Ok(msg)=rx.recv(){
// println!("{}",msg);
// }
let mut c:i32=0;
for x in rx{
println!("{}",x);
c+=1;
thread::sleep(Duration::from_secs(2));
}
println!("一共收到{c}个信息");
println!("子线程主线程全部结束。");
}
/*
the number is 1
the number is 5
the number is 2
the number is 3
the number is 6
the number is 7
the number is 9
the number is 8
the number is 10
the number is 4
一共收到10个信息
子线程主线程全部结束。
*/

该杂文来自: 最新技术

上一篇:rust之trait与impl与Box与dyn的联合示例

下一篇:rust匿名函数之Fn,FnMut,FnOnce的使用

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计