当前位置: 首页 > article >正文

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
}

 


http://www.kler.cn/news/341648.html

相关文章:

  • SPIE出版-EI会议-人机交互 虚拟现实 <<< 11月杭州
  • linux 重置root密码
  • 如何一键将数据库表导出为Excel,并且列名为中文注释
  • 【笔记】6.2 玻璃的成型
  • 文献阅读Prov-GigaPath模型--相关知识点罗列
  • 【React】setState 的同步异步问题
  • 汽车软件设计时容易忽略的点 -- 观ETAS Webinar有感
  • Windows系统安装Fooocus结合内网穿透实现公网环境远程生成AI图片
  • 『Mysql进阶』Mysql explain详解(五)
  • jQuery基础
  • ffmpeg面向对象——AVInputFormat与URLProtocol啥关系
  • AR虚拟试用,让网购不再只靠想象!
  • 新闻推荐系统:Spring Boot框架详解
  • PCB缺陷检测数据集 xml 可转yolo格式 ,共10688张图片
  • vue3.x系列之v-model的使用技巧及面试高频问题
  • Github 2024-10-06 php开源项目日报 Top10
  • 多种方式连接和管理 Oracle 数据库详解
  • 风口来了:有空可以考个人工智能证书!
  • k8s中pod的管理
  • 【ArcGIS/C#】调用控制台处理代码