You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

802 lines
85 KiB

<!DOCTYPE HTML>
<html lang="zh-CN" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>深入 async - Rust语言圣经(Rust Course)</title>
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" />
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../theme/style.css">
</head>
<body>
<!-- Provide site root to javascript -->
<script type="text/javascript">
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript">
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item affix "><a href="../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../community.html">社区和锈书</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></li></ol></li><li class="chapter-item "><a href="../basic/flow-control.html"><strong aria-hidden="true">2.5.</strong> 流程控制</a></li><li class="chapter-item "><a href="../basic/match-pattern/intro.html"><strong aria-hidden="true">2.6.</strong> 模式匹配</a><a class="toggle"><div></div></a></li><li>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/sunface/rust-course/edit/main/src/advance-practice/async.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
// Get viewed page store
var viewed_key = 'mdbook-viewed';
var viewed_map = {};
try {
var viewed_storage = localStorage.getItem(viewed_key);
if (viewed_storage) {
viewed_map = JSON.parse(viewed_storage)
}
} catch (e) { }
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
// Apply viewed style
if (viewed_map[link.pathname]) {
link.classList.add('md-viewed')
}
});
// Mark viewed after 30s
setTimeout(function() {
viewed_map[location.pathname] = 1;
localStorage.setItem(viewed_key, JSON.stringify(viewed_map));
}, 30000)
</script>
<div id="content" class="content">
<!-- Page table of contents -->
<div class="sidetoc"><nav class="pagetoc"></nav></div>
<main>
<h1 id="深入-tokio-背后的异步原理"><a class="header" href="#深入-tokio-背后的异步原理">深入 Tokio 背后的异步原理</a></h1>
<p>在经过多个章节的深入学习后Tokio 对我们来说不再是一座隐于云雾中的高山,它其实蛮简单好用的,甚至还有一丝丝的可爱!?</p>
<p>但从现在开始,如果想要进一步的深入 Tokio ,首先需要深入理解 <code>async</code> 的原理,其实我们在<a href="https://course.rs/async/intro.html">之前的章节</a>已经深入学习过,这里结合 Tokio 再来回顾下。</p>
<h2 id="future"><a class="header" href="#future">Future</a></h2>
<p>先来回顾一下 <code>async fn</code> 异步函数 :</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::net::TcpStream;
async fn my_async_fn() {
println!(&quot;hello from async&quot;);
// 通过 .await 创建 socket 连接
let _socket = TcpStream::connect(&quot;127.0.0.1:3000&quot;).await.unwrap();
println!(&quot;async TCP operation complete&quot;);
// 关闭socket
}
<span class="boring">}
</span></code></pre></pre>
<p>接着对它进行调用获取一个返回值,再在返回值上调用 <code>.await</code></p>
<pre><pre class="playground"><code class="language-rust edition2021">#[tokio::main]
async fn main() {
let what_is_this = my_async_fn();
// 上面的调用不会产生任何效果
// ... 执行一些其它代码
what_is_this.await;
// 直到 .await 后文本才被打印socket 连接也被创建和关闭
}
</code></pre></pre>
<p>在上面代码中 <code>my_async_fn</code> 函数为何可以惰性执行( 直到 .await 调用时才执行)?秘密就在于 <code>async fn</code> 声明的函数返回一个 <code>Future</code></p>
<p><code>Future</code> 是一个实现了 <a href="https://doc.rust-lang.org/std/future/trait.Future.html"><code>std::future::Future</code></a> 特征的值,该值包含了一系列异步计算过程,而这个过程直到 <code>.await</code> 调用时才会被执行。</p>
<p><code>std::future::Future</code> 的定义如下所示:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::pin::Pin;
use std::task::{Context, Poll};
pub trait Future {
type Output;
fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context)
-&gt; Poll&lt;Self::Output&gt;;
}
<span class="boring">}
</span></code></pre></pre>
<p>代码中有几个关键点:</p>
<ul>
<li><a href="https://course.rs/basic/trait/advance-trait.html#%E5%85%B3%E8%81%94%E7%B1%BB%E5%9E%8B">关联类型</a> <code>Output</code><code>Future</code> 执行完成后返回的值的类型</li>
<li><code>Pin</code> 类型是在异步函数中进行借用的关键,在<a href="https://course.rs/async/pin-unpin.html">这里</a>有非常详细的介绍</li>
</ul>
<p>和其它语言不同Rust 中的 <code>Future</code> 不代表一个发生在后台的计算,而是 <code>Future</code> 就代表了计算本身,因此
<code>Future</code> 的所有者有责任去推进该计算过程的执行,例如通过 <code>Future::poll</code> 函数。听上去好像还挺复杂?但是大家不必担心,因为这些都在 Tokio 中帮你自动完成了 :)</p>
<h4 id="实现-future"><a class="header" href="#实现-future">实现 Future</a></h4>
<p>下面来一起实现个五脏俱全的 <code>Future</code>它将1. 等待某个特定时间点的到来 2. 在标准输出打印文本 3. 生成一个字符串</p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
struct Delay {
when: Instant,
}
// 为我们的 Delay 类型实现 Future 特征
impl Future for Delay {
type Output = &amp;'static str;
fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;'_&gt;)
-&gt; Poll&lt;&amp;'static str&gt;
{
if Instant::now() &gt;= self.when {
// 时间到了Future 可以结束
println!(&quot;Hello world&quot;);
// Future 执行结束并返回 &quot;done&quot; 字符串
Poll::Ready(&quot;done&quot;)
} else {
// 目前先忽略下面这行代码
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
let when = Instant::now() + Duration::from_millis(10);
let future = Delay { when };
// 运行并等待 Future 的完成
let out = future.await;
// 判断 Future 返回的字符串是否是 &quot;done&quot;
assert_eq!(out, &quot;done&quot;);
}
</code></pre></pre>
<p>以上代码很清晰的解释了如何自定义一个 <code>Future</code>,并指定它如何通过 <code>poll</code> 一步一步执行,直到最终完成返回 <code>&quot;done&quot;</code> 字符串。</p>
<h4 id="async-fn-作为-future"><a class="header" href="#async-fn-作为-future">async fn 作为 Future</a></h4>
<p>大家有没有注意到,上面代码我们在 <code>main</code> 函数中初始化一个 <code>Future</code> 并使用 <code>.await</code> 对其进行调用执行,如果你是在 <code>fn main</code> 中这么做,是会报错的。</p>
<p>原因是 <code>.await</code> 只能用于 <code>async fn</code> 函数中,因此我们将 <code>main</code> 函数声明成 <code>async fn main</code> 同时使用 <code>#[tokio::main]</code> 进行了标注,此时 <code>async fn main</code> 生成的代码类似下面:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
enum MainFuture {
// 初始化,但永远不会被 poll
State0,
// 等待 `Delay` 运行,例如 `future.await` 代码行
State1(Delay),
// Future 执行完成
Terminated,
}
impl Future for MainFuture {
type Output = ();
fn poll(mut self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;'_&gt;)
-&gt; Poll&lt;()&gt;
{
use MainFuture::*;
loop {
match *self {
State0 =&gt; {
let when = Instant::now() +
Duration::from_millis(10);
let future = Delay { when };
*self = State1(future);
}
State1(ref mut my_future) =&gt; {
match Pin::new(my_future).poll(cx) {
Poll::Ready(out) =&gt; {
assert_eq!(out, &quot;done&quot;);
*self = Terminated;
return Poll::Ready(());
}
Poll::Pending =&gt; {
return Poll::Pending;
}
}
}
Terminated =&gt; {
panic!(&quot;future polled after completion&quot;)
}
}
}
}
}
<span class="boring">}
</span></code></pre></pre>
<p>可以看出,编译器会将 <code>Future</code> 变成状态机, 其中 <code>MainFuture</code> 包含了 <code>Future</code> 可能处于的状态:从 <code>State0</code> 状态开始,当 <code>poll</code> 被调用时, <code>Future</code> 会尝试去尽可能的推进内部的状态,若它可以被完成时,就会返回 <code>Poll::Ready</code>,其中还会包含最终的输出结果。</p>
<p><code>Future</code> 无法被完成,例如它所等待的资源还没有准备好,此时就会返回 <code>Poll::Pending</code>,该返回值会通知调用者: <code>Future</code> 会在稍后才能完成。</p>
<p>同时可以看到:当一个 <code>Future</code> 由其它 <code>Future</code> 组成时,调用外层 <code>Future</code><code>poll</code> 函数会同时调用一次内部 <code>Future</code><code>poll</code> 函数。</p>
<h2 id="执行器-excecutor-"><a class="header" href="#执行器-excecutor-">执行器( Excecutor )</a></h2>
<p><code>async fn</code> 返回 <code>Future</code> ,而后者需要通过被不断的 <code>poll</code> 才能往前推进状态,同时该 <code>Future</code> 还能包含其它 <code>Future</code> ,那么问题来了谁来负责调用最外层 <code>Future</code><code>poll</code> 函数?</p>
<p>回一下之前的内容,为了运行一个异步函数,我们必须使用 <code>tokio::spawn</code> 或 通过 <code>#[tokio::main]</code> 标注的 <code>async fn main</code> 函数。它们有一个非常重要的作用:将最外层 <code>Future</code> 提交给 Tokio 的执行器。该执行器负责调用 <code>poll</code> 函数,然后推动 <code>Future</code> 的执行,最终直至完成。</p>
<h4 id="mini-tokio"><a class="header" href="#mini-tokio">mini tokio</a></h4>
<p>为了更好理解相关的内容,我们一起来实现一个迷你版本的 Tokio完整的代码见<a href="https://github.com/tokio-rs/website/blob/master/tutorial-code/mini-tokio/src/main.rs">这里</a></p>
<p>先来看一段基础代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use futures::task;
fn main() {
let mut mini_tokio = MiniTokio::new();
mini_tokio.spawn(async {
let when = Instant::now() + Duration::from_millis(10);
let future = Delay { when };
let out = future.await;
assert_eq!(out, &quot;done&quot;);
});
mini_tokio.run();
}
struct MiniTokio {
tasks: VecDeque&lt;Task&gt;,
}
type Task = Pin&lt;Box&lt;dyn Future&lt;Output = ()&gt; + Send&gt;&gt;;
impl MiniTokio {
fn new() -&gt; MiniTokio {
MiniTokio {
tasks: VecDeque::new(),
}
}
/// 生成一个 Future并放入 mini-tokio 实例的任务队列中
fn spawn&lt;F&gt;(&amp;mut self, future: F)
where
F: Future&lt;Output = ()&gt; + Send + 'static,
{
self.tasks.push_back(Box::pin(future));
}
fn run(&amp;mut self) {
let waker = task::noop_waker();
let mut cx = Context::from_waker(&amp;waker);
while let Some(mut task) = self.tasks.pop_front() {
if task.as_mut().poll(&amp;mut cx).is_pending() {
self.tasks.push_back(task);
}
}
}
}
</code></pre></pre>
<p>以上代码运行了一个 <code>async</code> 语句块 <code>mini_tokio.spawn(async {...})</code> 还创建了一个 <code>Delay</code> 实例用于等待所需的时间。看上去相当不错,但这个实现有一个 <strong>重大缺陷</strong>:我们的执行器永远也不会休眠。执行器会持续的循环遍历所有的 <code>Future</code> ,然后不停的 <code>poll</code> 它们,但是事实上,大多数 <code>poll</code> 都是没有用的,因为此时 <code>Future</code> 并没有准备好,因此会继续返回 <code>Poll::Pending</code> ,最终这个循环遍历会让你的 CPU 疲于奔命,真打工人!</p>
<p>鉴于此,我们的 mini-tokio 只应该在 <code>Future</code> 准备好可以进一步运行后,才去 <code>poll</code> 它,例如该 <code>Future</code> 之前阻塞等待的<strong>资源</strong>已经准备好并可以被使用了,就可以对其进行 <code>poll</code>。再比如,如果一个 <code>Future</code> 任务在阻塞等待从 TCP socket 中读取数据,那我们只想在 <code>socket</code> 中有数据可以读取后才去 <code>poll</code> 它,而不是没事就 <code>poll</code> 着玩。</p>
<p>回到上面的代码中mini-tokio 只应该当任务的延迟时间到了后,才去 <code>poll</code> 它。 为了实现这个功能,我们需要 <code>通知 -&gt; 运行</code> 机制:当任务可以进一步被推进运行时,它会主动通知执行器,然后执行器再来 <code>poll</code></p>
<h2 id="waker"><a class="header" href="#waker">Waker</a></h2>
<p>一切的答案都在 <code>Waker</code> 中,资源可以用它来通知正在等待的任务:该资源已经准备好,可以继续运行了。</p>
<p>再来看下 <code>Future::poll</code> 的定义:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context)
-&gt; Poll&lt;Self::Output&gt;;
<span class="boring">}
</span></code></pre></pre>
<p><code>Context</code> 参数中包含有 <code>waker()</code>方法。该方法返回一个绑定到当前任务上的 <code>Waker</code>,然后 <code>Waker</code> 上定义了一个 <code>wake()</code> 方法,用于通知执行器相关的任务可以继续执行。</p>
<p>准确来说,当 <code>Future</code> 阻塞等待的资源已经准备好时(例如 socket 中有了可读取的数据),该资源可以调用 <code>wake()</code> 方法,来通知执行器可以继续调用该 <code>Future</code><code>poll</code> 函数来推进任务的执行。</p>
<h4 id="发送-wake-通知"><a class="header" href="#发送-wake-通知">发送 wake 通知</a></h4>
<p>现在,为 <code>Delay</code> 添加下 <code>Waker</code> 支持:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use std::thread;
struct Delay {
when: Instant,
}
impl Future for Delay {
type Output = &amp;'static str;
fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;'_&gt;)
-&gt; Poll&lt;&amp;'static str&gt;
{
if Instant::now() &gt;= self.when {
println!(&quot;Hello world&quot;);
Poll::Ready(&quot;done&quot;)
} else {
// 为当前任务克隆一个 waker 的句柄
let waker = cx.waker().clone();
let when = self.when;
// 生成一个计时器线程
thread::spawn(move || {
let now = Instant::now();
if now &lt; when {
thread::sleep(when - now);
}
waker.wake();
});
Poll::Pending
}
}
}
<span class="boring">}
</span></code></pre></pre>
<p>此时,计时器用来模拟一个阻塞等待的资源,一旦计时结束(该资源已经准备好),资源会通过 <code>waker.wake()</code> 调用通知执行器我们的任务再次被调度执行了。</p>
<p>当然,现在的实现还较为粗糙,等会我们会来进一步优化,在此之前,先来看看如何监听这个 <code>wake</code> 通知。</p>
<blockquote>
<p>当 Future 会返回 <code>Poll::Pending</code> 时,一定要确保 <code>wake</code> 能被正常调用,否则会导致任务永远被挂起,再也不会被执行器 <code>poll</code></p>
<p><strong>忘记在返回 <code>Poll::Pending</code> 时调用 <code>wake</code> 是很多难以发现 bug 的潜在源头!</strong></p>
</blockquote>
<p>再回忆下最早实现的 <code>Delay</code> 代码:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl Future for Delay {
type Output = &amp;'static str;
fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;'_&gt;)
-&gt; Poll&lt;&amp;'static str&gt;
{
if Instant::now() &gt;= self.when {
// 时间到了Future 可以结束
println!(&quot;Hello world&quot;);
// Future 执行结束并返回 &quot;done&quot; 字符串
Poll::Ready(&quot;done&quot;)
} else {
// 目前先忽略下面这行代码
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
<span class="boring">}
</span></code></pre></pre>
<p>在返回 <code>Poll::Pending</code> 之前,先调用了 <code>cx.waker().wake_by_ref()</code> ,由于此时我们还没有模拟计时资源,因此这里直接调用了 <code>wake</code> 进行通知,这样做会导致当前的 <code>Future</code> 被立即再次调度执行。</p>
<p>由此可见,这种通知的控制权是在你手里的,甚至可以像上面代码这样,还没准备好资源,就直接进行 <code>wake</code> 通知,但是总归意义不大,而且浪费了 CPU因为这种 <code>执行 -&gt; 立即通知再调度 -&gt; 执行</code> 的方式会造成一个非常繁忙的循环。</p>
<h4 id="处理-wake-通知"><a class="header" href="#处理-wake-通知">处理 wake 通知</a></h4>
<p>下面,让我们更新 mint-tokio 服务,让它能接收 wake 通知:当 <code>waker.wake()</code> 被调用后,相关联的任务会被放入执行器的队列中,然后等待执行器的调用执行。</p>
<p>为了实现这一点,我们将使用消息通道来排队存储这些被唤醒并等待调度的任务。有一点需要注意,从消息通道接收消息的线程(执行器所在的线程)和发送消息的线程(唤醒任务时所在的线程)可能是不同的,因此消息( <code>Waker</code> )必须要实现 <code>Send</code><code>Sync</code>,才能跨线程使用。</p>
<blockquote>
<p>关于 <code>Send</code><code>Sync</code> 的具体讲解见<a href="https://course.rs/advance/concurrency-with-threads/send-sync.html">这里</a></p>
</blockquote>
<p>基于以上理由,我们选择使用来自于 <code>crossbeam</code> 的消息通道,因为标准库中的消息通道不是 <code>Sync</code> 的。在 <code>Cargo.toml</code> 中添加以下依赖:</p>
<pre><code class="language-toml">crossbeam = &quot;0.8&quot;
</code></pre>
<p>再来更新下 <code>MiniTokio</code> 结构体:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use crossbeam::channel;
use std::sync::Arc;
struct MiniTokio {
scheduled: channel::Receiver&lt;Arc&lt;Task&gt;&gt;,
sender: channel::Sender&lt;Arc&lt;Task&gt;&gt;,
}
struct Task {
// 先空着,后面会填充代码
}
<span class="boring">}
</span></code></pre></pre>
<p><code>Waker</code> 实现了 <code>Sync</code> 特征,同时还可以被克隆,当 <code>wake</code> 被调用时,任务就会被调度执行。</p>
<p>为了实现上述的目的,我们引入了消息通道,当 <code>waker.wake()</code> 函数被调用时,任务会被发送到该消息通道中:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::sync::{Arc, Mutex};
struct Task {
// `Mutex` 是为了让 `Task` 实现 `Sync` 特征,它能保证同一时间只有一个线程可以访问 `Future`。
// 事实上 `Mutex` 并没有在 Tokio 中被使用,这里我们只是为了简化: Tokio 的真实代码实在太长了 :D
future: Mutex&lt;Pin&lt;Box&lt;dyn Future&lt;Output = ()&gt; + Send&gt;&gt;&gt;,
executor: channel::Sender&lt;Arc&lt;Task&gt;&gt;,
}
impl Task {
fn schedule(self: &amp;Arc&lt;Self&gt;) {
self.executor.send(self.clone());
}
}
<span class="boring">}
</span></code></pre></pre>
<p>接下来,我们需要让 <code>std::task::Waker</code> 能准确的找到所需的调度函数 关联起来,对此标准库中提供了一个底层的 API <a href="https://doc.rust-lang.org/std/task/struct.RawWakerVTable.html"><code>std::task::RawWakerVTable</code></a> 可以用于手动的访问 <code>vtable</code>,这种实现提供了最大的灵活性,但是需要大量 <code>unsafe</code> 的代码。</p>
<p>因此我们选择更加高级的实现:由 <code>futures</code> 包提供的 <a href="https://docs.rs/futures/0.3.19/futures/task/trait.ArcWake.html"><code>ArcWake</code></a> 特征,只要简单实现该特征,就可以将我们的 <code>Task</code> 转变成一个 <code>waker</code>。在 <code>Cargo.toml</code> 中添加以下包:</p>
<pre><code class="language-toml">futures = &quot;0.3&quot;
</code></pre>
<p>然后为我们的任务 <code>Task</code> 实现 <code>ArcWake</code>:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use futures::task::{self, ArcWake};
use std::sync::Arc;
impl ArcWake for Task {
fn wake_by_ref(arc_self: &amp;Arc&lt;Self&gt;) {
arc_self.schedule();
}
}
<span class="boring">}
</span></code></pre></pre>
<p>当之前的计时器线程调用 <code>waker.wake()</code> 时,所在的任务会被推入到消息通道中。因此接下来,我们需要实现接收端的功能,然后 <code>MiniTokio::run()</code> 函数中执行该任务:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl MiniTokio {
// 从消息通道中接收任务,然后通过 poll 来执行
fn run(&amp;self) {
while let Ok(task) = self.scheduled.recv() {
task.poll();
}
}
/// 初始化一个新的 mini-tokio 实例
fn new() -&gt; MiniTokio {
let (sender, scheduled) = channel::unbounded();
MiniTokio { scheduled, sender }
}
/// 在下面函数中,通过参数传入的 future 被 `Task` 包裹起来,然后会被推入到调度队列中,当 `run` 被调用时,该 future 将被执行
fn spawn&lt;F&gt;(&amp;self, future: F)
where
F: Future&lt;Output = ()&gt; + Send + 'static,
{
Task::spawn(future, &amp;self.sender);
}
}
impl Task {
fn poll(self: Arc&lt;Self&gt;) {
// 基于 Task 实例创建一个 waker, 它使用了之前的 `ArcWake`
let waker = task::waker(self.clone());
let mut cx = Context::from_waker(&amp;waker);
// 没有其他线程在竞争锁时,我们将获取到目标 future
let mut future = self.future.try_lock().unwrap();
// 对 future 进行 poll
let _ = future.as_mut().poll(&amp;mut cx);
}
// 使用给定的 future 来生成新的任务
//
// 新的任务会被推到 `sender` 中,接着该消息通道的接收端就可以获取该任务,然后执行
fn spawn&lt;F&gt;(future: F, sender: &amp;channel::Sender&lt;Arc&lt;Task&gt;&gt;)
where
F: Future&lt;Output = ()&gt; + Send + 'static,
{
let task = Arc::new(Task {
future: Mutex::new(Box::pin(future)),
executor: sender.clone(),
});
let _ = sender.send(task);
}
}
<span class="boring">}
</span></code></pre></pre>
<p>首先,我们实现了 <code>MiniTokio::run()</code> 函数,它会持续从消息通道中接收被唤醒的任务,然后通过 <code>poll</code> 来推动其继续执行。</p>
<p>其次,<code>MiniTokio::new()</code><code>MiniTokio::spawn()</code> 使用了消息通道而不是一个 <code>VecDeque</code> 。当新任务生成后,这些任务中会携带上消息通道的发送端,当任务中的资源准备就绪时,会使用该发送端将该任务放入消息通道的队列中,等待执行器 <code>poll</code></p>
<p><code>Task::poll()</code> 函数使用 <code>futures</code> 包提供的 <code>ArcWake</code> 创建了一个 <code>waker</code>,后者可以用来创建 <code>task::Context</code>,最终该 <code>Context</code> 会被传给执行器调用的 <code>poll</code> 函数。</p>
<blockquote>
<p>注意Task::poll 和执行器调用的 poll 是完全不同的,大家别搞混了</p>
</blockquote>
<h2 id="一些遗留问题"><a class="header" href="#一些遗留问题">一些遗留问题</a></h2>
<p>至此,我们的程序已经差不多完成,还剩几个遗留问题需要解决下。</p>
<h4 id="在异步函数中生成异步任务"><a class="header" href="#在异步函数中生成异步任务">在异步函数中生成异步任务</a></h4>
<p>之前实现 <code>Delay Future</code>我们提到有几个问题需要解决。Rust 的异步模型允许一个 Future 在执行过程中可以跨任务迁移:</p>
<pre><pre class="playground"><code class="language-rust edition2021">use futures::future::poll_fn;
use std::future::Future;
use std::pin::Pin;
#[tokio::main]
async fn main() {
let when = Instant::now() + Duration::from_millis(10);
let mut delay = Some(Delay { when });
poll_fn(move |cx| {
let mut delay = delay.take().unwrap();
let res = Pin::new(&amp;mut delay).poll(cx);
assert!(res.is_pending());
tokio::spawn(async move {
delay.await;
});
Poll::Ready(())
}).await;
}
</code></pre></pre>
<p>首先,<code>poll_fn</code> 函数使用闭包创建了一个 <code>Future</code>,其次,上面代码还创建一个 <code>Delay</code> 实例,然后在闭包中,对其进行了一次 <code>poll</code> ,接着再将该 <code>Delay</code> 实例发送到一个新的任务,在此任务中使用 <code>.await</code> 进行了执行。</p>
<p>在例子中,<code>Delay:poll</code> 被调用了不止一次,且使用了不同的 <code>Waker</code> 实例,在这种场景下,你必须确保调用最近一次 <code>poll</code> 函数中的 <code>Waker</code> 参数中的<code>wake</code>方法。也就是调用最内层 <code>poll</code> 函数参数( <code>Waker</code> )上的 <code>wake</code> 方法。</p>
<p>当实现一个 <code>Future</code> 时,很关键的一点就是要假设每次 <code>poll</code> 调用都会应用到一个不同的 <code>Waker</code> 实例上。因此 <code>poll</code> 函数必须要使用一个新的 <code>waker</code> 去更新替代之前的 <code>waker</code></p>
<p>我们之前的 <code>Delay</code> 实现中,会在每一次 <code>poll</code> 调用时都生成一个新的线程。这么做问题不大,但是当 <code>poll</code> 调用较多时会出现明显的性能问题!一个解决方法就是记录你是否已经生成了一个线程,然后只有在没有生成时才去创建一个新的线程。但是一旦这么做,就必须确保线程的 <code>Waker</code> 在后续 <code>poll</code> 调用中被正确更新,否则你无法唤醒最近的 <code>Waker</code> </p>
<p>这一段大家可能会看得云里雾里的,没办法,原文就饶来绕去,好在终于可以看代码了。。我们可以通过代码来解决疑惑:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::thread;
use std::time::{Duration, Instant};
struct Delay {
when: Instant,
// 用于说明是否已经生成一个线程
// Some 代表已经生成, None 代表还没有
waker: Option&lt;Arc&lt;Mutex&lt;Waker&gt;&gt;&gt;,
}
impl Future for Delay {
type Output = ();
fn poll(mut self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;'_&gt;) -&gt; Poll&lt;()&gt; {
// 若这是 Future 第一次被调用,那么需要先生成一个计时器线程。
// 若不是第一次调用(该线程已在运行),那要确保已存储的 `Waker` 跟当前任务的 `waker` 匹配
if let Some(waker) = &amp;self.waker {
let mut waker = waker.lock().unwrap();
// 检查之前存储的 `waker` 是否跟当前任务的 `waker` 相匹配.
// 这是必要的,原因是 `Delay Future` 的实例可能会在两次 `poll` 之间被转移到另一个任务中,然后
// 存储的 waker 被该任务进行了更新。
// 这种情况一旦发生,`Context` 包含的 `waker` 将不同于存储的 `waker`。
// 因此我们必须对存储的 `waker` 进行更新
if !waker.will_wake(cx.waker()) {
*waker = cx.waker().clone();
}
} else {
let when = self.when;
let waker = Arc::new(Mutex::new(cx.waker().clone()));
self.waker = Some(waker.clone());
// 第一次调用 `poll`,生成计时器线程
thread::spawn(move || {
let now = Instant::now();
if now &lt; when {
thread::sleep(when - now);
}
// 计时结束,通过调用 `waker` 来通知执行器
let waker = waker.lock().unwrap();
waker.wake_by_ref();
});
}
// 一旦 waker 被存储且计时器线程已经开始,我们就需要检查 `delay` 是否已经完成
// 若计时已完成,则当前 Future 就可以完成并返回 `Poll::Ready`
if Instant::now() &gt;= self.when {
Poll::Ready(())
} else {
// 计时尚未结束Future 还未完成,因此返回 `Poll::Pending`.
//
// `Future` 特征要求当 `Pending` 被返回时,那我们要确保当资源准备好时,必须调用 `waker` 以通
// 知执行器。 在我们的例子中,会通过生成的计时线程来保证
//
// 如果忘记调用 waker 那等待我们的将是深渊:该任务将被永远的挂起,无法再执行
Poll::Pending
}
}
}
<span class="boring">}
</span></code></pre></pre>
<p>这着实有些复杂(原文。。),但是简单来看就是:在每次 <code>poll</code> 调用时,都会检查 <code>Context</code> 中提供的 <code>waker</code> 和我们之前记录的 <code>waker</code> 是否匹配。若匹配,就什么都不用做,若不匹配,那之前存储的就必须进行更新。</p>
<h4 id="notify"><a class="header" href="#notify">Notify</a></h4>
<p>我们之前证明了如何用手动编写的 <code>waker</code> 来实现 <code>Delay Future</code><code>Waker</code> 是 Rust 异步编程的基石,因此绝大多数时候,我们并不需要直接去使用它。例如,在 <code>Delay</code> 的例子中, 可以使用 <a href="https://docs.rs/tokio/1.16.0/tokio/sync/struct.Notify.html"><code>tokio::sync::Notify</code></a> 去实现。</p>
<p><code>Notify</code> 提供了一个基础的任务通知机制,它会处理这些 <code>waker</code> 的细节,包括确保两次 <code>waker</code> 的匹配:</p>
<pre><pre class="playground"><code class="language-rust edition2021">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::sync::Notify;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::thread;
async fn delay(dur: Duration) {
let when = Instant::now() + dur;
let notify = Arc::new(Notify::new());
let notify2 = notify.clone();
thread::spawn(move || {
let now = Instant::now();
if now &lt; when {
thread::sleep(when - now);
}
notify2.notify_one();
});
notify.notified().await;
}
<span class="boring">}
</span></code></pre></pre>
<p>当使用 <code>Notify</code> 后,我们就可以轻松的实现如上的 <code>delay</code> 函数。</p>
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
<p>在看完这么长的文章后,我们来总结下,否则大家可能还会遗忘:</p>
<ul>
<li>在 Rust 中,<code>async</code> 是惰性的,直到执行器 <code>poll</code> 它们时,才会开始执行</li>
<li><code>Waker</code><code>Future</code> 被执行的关键,它可以链接起 <code>Future</code> 任务和执行器</li>
<li>当资源没有准备时,会返回一个 <code>Poll::Pending</code></li>
<li>当资源准备好时,会通过 <code>waker.wake</code> 发出通知</li>
<li>执行器会收到通知,然后调度该任务继续执行,此时由于资源已经准备好,因此任务可以顺利往前推进了</li>
</ul>
<div id="giscus-container"></div>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../advance-practice/frame.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../advance-practice/select.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../advance-practice/frame.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../advance-practice/select.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script type="text/javascript">
window.playground_copyable = true;
</script>
<script src="../ace.js" type="text/javascript" charset="utf-8"></script>
<script src="../editor.js" type="text/javascript" charset="utf-8"></script>
<script src="../mode-rust.js" type="text/javascript" charset="utf-8"></script>
<script src="../theme-dawn.js" type="text/javascript" charset="utf-8"></script>
<script src="../theme-tomorrow_night.js" type="text/javascript" charset="utf-8"></script>
<script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="../book.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "advance-practice/async.md"
</script>
<!-- Custom JS scripts -->
<script type="text/javascript" src="../assets/custom.js"></script>
<script type="text/javascript" src="../assets/bigPicture.js"></script>
</body>
</html>