rust之impl Mutex impl struct tokio async await多线程异步共享及设置struct值的综合实例
Admin | 2023-3-12 21:38:58 | 被阅次数 | 1064
如题所示,代码如下:
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"
*/