rust语言tokio库底层原理解析

目录

更新中-2024-02-08

1 rust版本及tokio版本说明

rust版本为1.60

bash 复制代码
[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

bash 复制代码
[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工作线程。如下:

rust 复制代码
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)],如下所示:

rust 复制代码
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

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

rust 复制代码
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!");
    });
}

更易理解的写法为如下:

rust 复制代码
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。如下所示:

rust 复制代码
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()函数的入参,如下所示:

rust 复制代码
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!");
    });
}

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

rust 复制代码
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结构体

rust 复制代码
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结构体如下:

rust 复制代码
// 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语法后生成一个完美的目录。

如何改变文本的样式

强调文本 强调文本

加粗文本 加粗文本

标记文本

删除文本

引用文本

H~2~O is是液体。

2^10^ 运算结果是 1024.

插入链接与图片

链接: link.

图片:

带尺寸的图片:

居中的图片:

居中并且带尺寸的图片:

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

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

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

javascript 复制代码
// An highlighted block
var foo = 'bar';

生成一个适合你的列表

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

创建一个表格

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

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

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

使用:---------:居中

使用:----------居左

使用----------:居右

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

SmartyPants

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

TYPE ASCII
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

创建一个自定义列表

:
Text-to- conversion tool
:
John
:
Luke

如何创建一个注脚

一个具有注脚的文本。^2^

注释也是必不可少的

Markdown将文本转换为 。

KaTeX数学公式

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

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

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

你可以找到更多关于的信息 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. 注脚的解释 ↩︎

*[HTML]: 超文本标记语言

相关推荐
许野平15 小时前
Rust: Warp RESTful API 如何得到客户端IP?
tcp/ip·rust·restful·ip地址
许野平18 小时前
Rust:Result 和 Error
开发语言·后端·rust·error·result
Freestyle Coding20 小时前
使用rust自制操作系统内核
c语言·汇编·microsoft·rust·操作系统
许野平2 天前
Rust 编译器使用的 C++ 编译器吗?
c++·rust
怪我冷i2 天前
Rust GUI框架Tauri V1 入门
rust
新知图书2 天前
Rust的常量
算法·机器学习·rust
白总Server2 天前
php语言基本语法
开发语言·ide·后端·golang·rust·github·php
凄凄迷人2 天前
前端基于Rust实现的Wasm进行图片压缩的技术文档
前端·rust·wasm·图片压缩
winddevil2 天前
[rCore学习笔记 027]地址空间
rust·嵌入式·rcore
bluebonnet273 天前
【Rust练习】15.match 和 if let
开发语言·后端·rust