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

rust语言tokio库底层原理解析

目录

  • 1 rust版本及tokio版本说明
  • 1 tokio简介
  • 2 tokio::main
    • 2.1 tokio::main使用多线程模式
    • 2.2 tokio::main使用单线程模式
  • 3 builder.build()函数
    • 3.1 build_threaded_runtime()函数
    • 新的改变
    • 功能快捷键
    • 合理的创建标题,有助于目录的生成
    • 如何改变文本的样式
    • 插入链接与图片
    • 如何插入一段漂亮的代码片
    • 生成一个适合你的列表
    • 创建一个表格
      • 设定内容居中、居左、居右
      • SmartyPants
    • 创建一个自定义列表
    • 如何创建一个注脚
    • 注释也是必不可少的
    • KaTeX数学公式
    • 新的甘特图功能,丰富你的文章
    • UML 图表
    • FLowchart流程图
    • 导出与导入
      • 导出
      • 导入

更新中-2024-02-08

1 rust版本及tokio版本说明

rust版本为1.60

[10307750@zte.intra@LIN-9AC90CF34F9 ~]$ cargo --version
cargo 1.60.0 (d1fd9fe 2022-03-01)
[10307750@zte.intra@LIN-9AC90CF34F9 ~]$ rustup --version
rustup 1.26.0 (5af9b9484 2023-04-05)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.60.0 (7737e0b5c 2022-04-04)`
[10307750@zte.intra@LIN-9AC90CF34F9 ~]$ rustup toolchain list
stable-x86_64-unknown-linux-gnu
nightly-x86_64-unknown-linux-gnu
1.59-x86_64-unknown-linux-gnu
1.60-x86_64-unknown-linux-gnu (default)
1.64-x86_64-unknown-linux-gnu
1.65-x86_64-unknown-linux-gnu

tokio版本为1.0.0

[package]
name = "rust_tokio"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "1.0.0", features = ["full"] }

1 tokio简介

2 tokio::main

当我们要使用tokio库时,需要在主函数上定义tokio::main,如下所示:

2.1 tokio::main使用多线程模式

多线程模式即main函数为主线程,另外还有一些worker工作线程。如下:

use tokio;

#[tokio::main]
async fn main() {
    tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
    println!("hello world!");
}

这个#[tokio::main]宏定义实际上是#[tokio::main(flavor = "multi_thread", worker_threads = 7)],如下所示:

use tokio;

#[tokio::main(flavor = "multi_thread", worker_threads = 7)]
async fn main() {
    tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
    println!("hello world!");
}

flavor="multi_thread"表示当前使用的是多线程模式,worker_threads=7表示产生7个工作线程。#[tokio::main]宏定义如果没有手动指定worker_threads数量,tokio则会自动生成worker_threads数量,该数量主要与当前运行环境的CPU数量有关,其对应关系为1个cpu core对应1个worker_thread工作线程。即worker_thread_nums = CPU core nums

上述代码随后会被展开,展开成如下代码:

fn main() {
    let mut builder = tokio::runtime::Builder::new_multi_thread();
    let runtime = builder.enable_all().build().unwrap();
    runtime.block_on(async {
        tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
        println!("hello world!");
    });
}

更易理解的写法为如下:

use tokio;

fn main() {
	// 创建一个builder,设置为multi_thread模式,此时的线程数量还为None
    let mut builder = tokio::runtime::Builder::new_multi_thread();
    // 构建tokio的runtime运行时,创建线程池,数量为worker_thread nums = cpu core 
    let runtime = builder.enable_all().build().unwrap();
    // block_on函数是真正执行自己写的代码的部分,为阻塞式运行
    // 只有当block_on中的内容完全执行结束才会继续执行main函数block_on后面的内容
    runtime.block_on(tokio_main());
}

// 自己的main函数逻辑代码
async fn tokio_main() {
    tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
    println!("hello world!");
}

2.2 tokio::main使用单线程模式

单线程模式的意思则是只有main一个线程,没有worker_thread工作线程,且在后续的使用中,也不会去创建worker_thread工作线程。单线程模式必须手动在#[tokio::main]宏定义中指定current_thread。如下所示:

use tokio;

#[tokio::main(flavor = "current_thread")]
async fn main() {
    tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
    println!("hello world!");
}

在上述代码中,定义了一个async块,为main()函数,这个async块则会在代码展开的时候,作为runtime.block_on()函数的入参,如下所示:

use tokio;

fn main() {
	// 创建一个builder,设置为current_thread模式
    let mut builder = tokio::runtime::Builder::new_current_thread();
    // 构建tokio的runtime运行时
    let runtime = builder.enable_all().build().unwrap();
    // block_on函数是真正执行自己写的代码的部分,为阻塞式运行
    // 只有当block_on中的内容完全执行结束才会继续执行main函数block_on后面的内容
    runtime.block_on(async {
        tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
        println!("hello world!");
    });
}

或者写成如下格式更好理解:

use tokio;

fn main() {
	// 创建一个builder,设置为current_thread模式
    let mut builder = tokio::runtime::Builder::new_current_thread();
    // 构建tokio的runtime运行时
    let runtime = builder.enable_all().build().unwrap();
    // block_on函数是真正执行自己写的代码的部分,为阻塞式运行
    // 只有当block_on中的内容完全执行结束才会继续执行main函数block_on后面的内容
    runtime.block_on(tokio_main());
}

// 自己的main函数逻辑代码
async fn tokio_main() {
    tokio::time::sleep(tokio::time::Duration::new(1, 0)).await;
    println!("hello world!");
}

3 builder.build()函数

build函数会调用build_threaded_runtime创建多线程模式

3.1 build_threaded_runtime()函数

调用create_blocking_pool函数
BlockingPool::new()函数则会创建一个BlockPool结构体,这个结构体中有一个Shared结构体

pub(crate) fn new(builder: &Builder, thread_cap: usize) -> BlockingPool {
        let (shutdown_tx, shutdown_rx) = shutdown::channel();
        let keep_alive = builder.keep_alive.unwrap_or(KEEP_ALIVE);

        BlockingPool {
            spawner: Spawner {
                inner: Arc::new(Inner {
                	// 创建shared结构体
                    shared: Mutex::new(Shared {
                        queue: VecDeque::new(),
                        num_th: 0,
                        num_idle: 0,
                        num_notify: 0,
                        shutdown: false,
                        shutdown_tx: Some(shutdown_tx),
                        last_exiting_thread: None,
                        worker_threads: HashMap::new(),
                        worker_thread_index: 0,
                    }),
                    condvar: Condvar::new(),
                    thread_name: builder.thread_name.clone(),
                    stack_size: builder.thread_stack_size,
                    after_start: builder.after_start.clone(),
                    before_stop: builder.before_stop.clone(),
                    thread_cap,
                    keep_alive,
                }),
            },
            shutdown_rx,
        }
    }

Shared结构体如下:

// BlockingPool线程池中共享的一些数据结构
struct Shared {
	// queue队列,BlockingPool线程池中的线程会从这个queue中取task
    queue: VecDeque<Task>,
    // 一共有num_th个线程
    num_th: usize,
    // 有num_idle个线程处于闲置状态,什么事情都没干
    num_idle: u32,
    // 有num_notify个线程被通知有任务可以拿来处理,即有num_notify个线程处于忙碌中。
    num_notify: u32,
    // 线程池shutdown相关的事情。
    shutdown: bool,
    shutdown_tx: Option<shutdown::Sender>,
    /// Prior to shutdown, we clean up JoinHandles by having each timed-out
    /// thread join on the previous timed-out thread. This is not strictly
    /// necessary but helps avoid Valgrind false positives, see
    /// https://github.com/tokio-rs/tokio/commit/646fbae76535e397ef79dbcaacb945d4c829f666
    /// for more information.
    last_exiting_thread: Option<thread::JoinHandle<()>>,
    /// This holds the JoinHandles for all running threads; on shutdown, the thread
    /// calling shutdown handles joining on these.
    // 所有的worker_thread
    worker_threads: HashMap<usize, thread::JoinHandle<()>>,
    /// This is a counter used to iterate worker_threads in a consistent order (for loom's
    /// benefit)
    worker_thread_index: usize,
}

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

新的改变

我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:

  1. 全新的界面设计 ,将会带来全新的写作体验;
  2. 在创作中心设置你喜爱的代码高亮样式,Markdown 将代码片显示选择的高亮样式 进行展示;
  3. 增加了 图片拖拽 功能,你可以将本地的图片直接拖拽到编辑区域直接展示;
  4. 全新的 KaTeX数学公式 语法;
  5. 增加了支持甘特图的mermaid语法1 功能;
  6. 增加了 多屏幕编辑 Markdown文章功能;
  7. 增加了 焦点写作模式、预览模式、简洁写作模式、左右区域同步滚轮设置 等功能,功能按钮位于编辑区域与预览区域中间;
  8. 增加了 检查列表 功能。

功能快捷键

撤销:Ctrl/Command + Z
重做:Ctrl/Command + Y
加粗:Ctrl/Command + B
斜体:Ctrl/Command + I
标题:Ctrl/Command + Shift + H
无序列表:Ctrl/Command + Shift + U
有序列表:Ctrl/Command + Shift + O
检查列表:Ctrl/Command + Shift + C
插入代码:Ctrl/Command + Shift + K
插入链接:Ctrl/Command + Shift + L
插入图片:Ctrl/Command + Shift + G
查找:Ctrl/Command + F
替换:Ctrl/Command + G

合理的创建标题,有助于目录的生成

直接输入1次#,并按下space后,将生成1级标题。
输入2次#,并按下space后,将生成2级标题。
以此类推,我们支持6级标题。有助于使用TOC语法后生成一个完美的目录。

如何改变文本的样式

强调文本 强调文本

加粗文本 加粗文本

标记文本

删除文本

引用文本

H2O is是液体。

210 运算结果是 1024.

插入链接与图片

链接: link.

图片: Alt

带尺寸的图片: Alt

居中的图片: Alt

居中并且带尺寸的图片: Alt

当然,我们为了让用户更加便捷,我们增加了图片拖拽功能。

如何插入一段漂亮的代码片

去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

// An highlighted block
var foo = 'bar';

生成一个适合你的列表

  • 项目
    • 项目
      • 项目
  1. 项目1
  2. 项目2
  3. 项目3
  • 计划任务
  • 完成任务

创建一个表格

一个简单的表格是这么创建的:

项目Value
电脑$1600
手机$12
导管$1

设定内容居中、居左、居右

使用:---------:居中
使用:----------居左
使用----------:居右

第一列第二列第三列
第一列文本居中第二列文本居右第三列文本居左

SmartyPants

SmartyPants将ASCII标点字符转换为“智能”印刷标点HTML实体。例如:

TYPEASCIIHTML
Single backticks'Isn't this fun?'‘Isn’t this fun?’
Quotes"Isn't this fun?"“Isn’t this fun?”
Dashes-- is en-dash, --- is em-dash– is en-dash, — is em-dash

创建一个自定义列表

Markdown
Text-to- HTML conversion tool
Authors
John
Luke

如何创建一个注脚

一个具有注脚的文本。2

注释也是必不可少的

Markdown将文本转换为 HTML

KaTeX数学公式

您可以使用渲染LaTeX数学表达式 KaTeX:

Gamma公式展示 Γ ( n ) = ( n − 1 ) ! ∀ n ∈ N \Gamma(n) = (n-1)!\quad\forall n\in\mathbb N Γ(n)=(n1)!nN 是通过欧拉积分

Γ ( z ) = ∫ 0 ∞ t z − 1 e − t d t   . \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. Γ(z)=0tz1etdt.

你可以找到更多关于的信息 LaTeX 数学表达式here.

新的甘特图功能,丰富你的文章

2014-01-07 2014-01-09 2014-01-11 2014-01-13 2014-01-15 2014-01-17 2014-01-19 2014-01-21 已完成 进行中 计划一 计划二 现有任务 Adding GANTT diagram functionality to mermaid
  • 关于 甘特图 语法,参考 这儿,

UML 图表

可以使用UML图表进行渲染。 Mermaid. 例如下面产生的一个序列图:

张三 李四 王五 你好!李四, 最近怎么样? 你最近怎么样,王五? 我很好,谢谢! 我很好,谢谢! 李四想了很长时间, 文字太长了 不适合放在一行. 打量着王五... 很好... 王五, 你怎么样? 张三 李四 王五

这将产生一个流程图。:

链接
长方形
圆角长方形
菱形
  • 关于 Mermaid 语法,参考 这儿,

FLowchart流程图

我们依旧会支持flowchart的流程图:

Created with Raphaël 2.3.0 开始 我的操作 确认? 结束 yes no
  • 关于 Flowchart流程图 语法,参考 这儿.

导出与导入

导出

如果你想尝试使用此编辑器, 你可以在此篇文章任意编辑。当你完成了一篇文章的写作, 在上方工具栏找到 文章导出 ,生成一个.md文件或者.html文件进行本地保存。

导入

如果你想加载一篇你写过的.md文件,在上方工具栏可以选择导入功能进行对应扩展名的文件导入,
继续你的创作。


  1. mermaid语法说明 ↩︎

  2. 注脚的解释 ↩︎


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

相关文章:

  • Linux查询指令
  • PneumoLLM:少样本大模型诊断尘肺病新方法
  • Android 13.0 系统framework修改低电量关机值为3%
  • Python HttpServer 之 简单快速搭建本地服务器,并且使用 requests 测试访问下载服务器文件
  • 医学图像隐私保护
  • OCP使用CLI创建和构建应用
  • vue3 之 商城项目—登陆
  • 政安晨:示例演绎TensorFlow的官方指南(三){快速使用数据可视化工具TensorBoard}
  • JSP编程
  • MySQL ——group by子句使用with rollup
  • npm 下载报错
  • 利用LLM大模型生成sql的深入应用探究
  • nvm安装node后,npm无效
  • “Hopf Oscillator-Based Gait Transition for A Quadruped Robot“代码复现
  • 春节:当代发展及创新传承
  • 揭开Markdown的秘籍:标题|文字样式|列表
  • c#cad 创建-圆(二)
  • 飞天使-k8s知识点13-kubernetes散装知识点2-statefulsetdaemonset
  • Red Panda Dev C++ Maker 使用说明
  • 攻防世界 CTF Web方向 引导模式-难度1 —— 1-10题 wp精讲
  • Git远程仓库的使用(Gitee)及相关指令
  • 【初中生讲机器学习】6. 分类算法中常用的模型评价指标有哪些?here!
  • 《游戏引擎架构》 -- 学习2
  • curl8.6.0 - CURLE_PEER_FAILED_VERIFICATION
  • Linux——进程间通信:管道
  • VUE学习——事件修饰符
  • npm淘宝镜像源换新地址
  • 如何使用Python + 百度翻译API 自动大批量免费翻译Excel文件中的外语内容
  • Modelsim10.4安装
  • 1123. 铲雪车(欧拉回路)