Dzwebs.Net

撰写电脑技术杂文十余年

rust之impl Mutex impl struct tokio async await多线程异步共享及设置struct值的综合实例

Admin | 2023-3-12 21:38:58 | 被阅次数 | 842

温馨提示!

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

  如题所示,代码如下:

use std::sync::{Arc,Mutex};
#[derive(Debug)]
struct MyInfor{
name:String,
}
impl MyInfor{
fn set(&mut self,s:String){
self.name = String::from(s);
}
fn getname(&self) -> &str{
&self.name
}
}
#[tokio::main]
async fn main(){
let mut haddles = vec![];
for i in 1..=1000{
println!("循环次数:{}",i);
let t = tokio::spawn(async move{
modifyname(i).await;
});
haddles.push(t);
}
for t in haddles{
tokio::join!(t);
}
println!("全部结束…");
}
async fn modifyname(i:i32)->String{
if i==997{
std::thread::sleep(std::time::Duration::from_secs(10));
}
let myname = Arc::new(Mutex::new(MyInfor{name:String::from("hello rust.".to_owned()+&i.to_string())}));
println!("初始值:{:?}",myname.lock().unwrap());
let mutname = myname.clone();
{
let rename = mutname.lock().unwrap().set("rust hello.".to_string()+&i.to_string());
}
println!("修改值:{:?}",myname.lock().unwrap().name);
println!("获取值:{:?}",myname.lock().unwrap().getname());
"good.".to_string()
}
/*输出如下内容
循环次数:1
循环次数:2
循环次数:3
初始值:MyInfor { name: "hello rust.2" }
循环次数:4
循环次数:5
初始值:MyInfor { name: "hello rust.1" }
修改值:"rust hello.2"
获取值:"rust hello.2"
初始值:MyInfor { name: "hello rust.3" }
循环次数:6
初始值:MyInfor { name: "hello rust.5" }
修改值:"rust hello.1"
获取值:"rust hello.1"
修改值:"rust hello.3"
获取值:"rust hello.3"
初始值:MyInfor { name: "hello rust.6" }
修改值:"rust hello.5"
获取值:"rust hello.5"
循环次数:7
修改值:"rust hello.6"
获取值:"rust hello.6"
*/


该杂文来自: 最新技术

上一篇:rust之PathBuf获取默认根目录及添加目录和获取某

下一篇:rust泛型T构造枚举enum的通用字段及impl构造自定

网站备案号:

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

版权属性:

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

联系方式:

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