rust使用tokio
Rust 是一种系统编程语言,它强调安全、并发和高性能。tokio 是一个基于 Rust 的异步运行时库,专门用于构建异步应用程序。使用 tokio 可以轻松地管理异步任务,并实现高效的并发。
添加依赖:
cargo add tokio -F full
示例:
示例1:
fn main() {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
println!("Hello World!!!");
});
}
示例2:
多线程初始化:
use tokio::runtime::Builder;
fn main() {
let rt = Builder::new_multi_thread()
.worker_threads(8)
.thread_name("udaiot1000")
.thread_stack_size(3 * 1024 * 1024)
.build()
.unwrap();
rt.block_on(async {
println!("Hello World!!!");
});
}
示例3:
单线程初始化:
use tokio::runtime::Builder;
fn main() {
let rt = Builder::new_current_thread().build().unwrap();
rt.block_on(async {
println!("Hello World!!!");
});
}
示例4:
使用#[tokio::main]默认使用多线程,等价于使用多线程的模式
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
hello().await;
hello().await;
async {
println!("我是多线程异步代码块!!!");
}
.await;
}
async fn hello() {
sleep(Duration::from_secs(3)).await;
println!("hello");
}
示例5:
spawn:
Tokio任务是一个异步的绿色线程。它们是由tokio::spawn传递async代码块创建的。
调用spawn它会生成一个新的异步任务,它会马上执行,并且返回JoinHandle,可以用await或者join!等待执行完毕
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let j1 = tokio::spawn(async {
println!("hello j1");
sleep(Duration::from_secs(3)).await;
});
let j2 = tokio::spawn(async {
println!("hello j2");
sleep(Duration::from_secs(3)).await;
200
});
let r1 = j1.await;
let r2 = j2.await;
println!("{:?}", r1.unwrap());
println!("{:?}", r2.unwrap());
}
join!:
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let j1 = tokio::spawn(async {
println!("hello j1");
sleep(Duration::from_secs(3)).await;
});
let j2 = tokio::spawn(async {
println!("hello j2");
sleep(Duration::from_secs(3)).await;
200
});
// let r1 = j1.await;
// let r2 = j2.await;
let (r1, r2) = tokio::join!(j1, j2);
println!("{:?}", r1.unwrap());
println!("{:?}", r2.unwrap());
}
try_join!:
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let res = tokio::try_join!(j1(), j2());
match res {
Ok((a, b)) => println!("{:?} {:?}", a, b),
Err(err) => println!("{:?}", err),
}
}
async fn j1() -> Result<(), &'static str> {
println!("j1");
sleep(Duration::from_secs(2)).await;
Err("出错")
}
async fn j2() -> Result<(), &'static str> {
println!("j2");
sleep(Duration::from_secs(3)).await;
Ok(())
}
select!:
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::select! {
value = j1() =>{
println!("我先执行完 => j1 : {:?}", value);
}
value = j2() =>{
println!("我先执行完 => j2 : {:?}", value);
}
}
}
async fn j1() -> i32 {
println!("j1");
sleep(Duration::from_secs(2)).await;
200
}
async fn j2() -> i32 {
println!("j2");
sleep(Duration::from_secs(3)).await;
300
}