|
|
<!DOCTYPE HTML>
|
|
|
<html lang="zh-CN" class="light sidebar-visible" dir="ltr">
|
|
|
<head>
|
|
|
<!-- Book generated using mdBook -->
|
|
|
<meta charset="UTF-8">
|
|
|
<title>深入 async - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
|
<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-de23e50b.svg">
|
|
|
<link rel="shortcut icon" href="../favicon-8114d1fc.png">
|
|
|
<link rel="stylesheet" href="../css/variables-8adf115d.css">
|
|
|
<link rel="stylesheet" href="../css/general-2459343d.css">
|
|
|
<link rel="stylesheet" href="../css/chrome-ae938929.css">
|
|
|
<link rel="stylesheet" href="../css/print-9e4910d8.css" media="print">
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
<link rel="stylesheet" href="../fonts/fonts-9644e21d.css">
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
<link rel="stylesheet" id="mdbook-highlight-css" href="../highlight-493f70e1.css">
|
|
|
<link rel="stylesheet" id="mdbook-tomorrow-night-css" href="../tomorrow-night-4c0ae647.css">
|
|
|
<link rel="stylesheet" id="mdbook-ayu-highlight-css" href="../ayu-highlight-3fdfc3ac.css">
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
<link rel="stylesheet" href="../theme/style-78591068.css">
|
|
|
|
|
|
|
|
|
<!-- Provide site root and default themes to javascript -->
|
|
|
<script>
|
|
|
const path_to_root = "../";
|
|
|
const default_light_theme = "light";
|
|
|
const default_dark_theme = "navy";
|
|
|
window.path_to_searchindex_js = "../searchindex-4a1a74fa.js";
|
|
|
</script>
|
|
|
<!-- Start loading toc.js asap -->
|
|
|
<script src="../toc-42887675.js"></script>
|
|
|
</head>
|
|
|
<body>
|
|
|
<div id="mdbook-help-container">
|
|
|
<div id="mdbook-help-popup">
|
|
|
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
|
|
|
<div>
|
|
|
<p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p>
|
|
|
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
|
|
|
<p>Press <kbd>?</kbd> to show this help</p>
|
|
|
<p>Press <kbd>Esc</kbd> to hide this help</p>
|
|
|
</div>
|
|
|
</div>
|
|
|
</div>
|
|
|
<div id="mdbook-body-container">
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
<script>
|
|
|
try {
|
|
|
let theme = localStorage.getItem('mdbook-theme');
|
|
|
let 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>
|
|
|
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
|
|
|
let theme;
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
const html = document.documentElement;
|
|
|
html.classList.remove('light')
|
|
|
html.classList.add(theme);
|
|
|
html.classList.add("js");
|
|
|
</script>
|
|
|
|
|
|
<input type="checkbox" id="mdbook-sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
<script>
|
|
|
let sidebar = null;
|
|
|
const sidebar_toggle = document.getElementById("mdbook-sidebar-toggle-anchor");
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
sidebar = sidebar || 'visible';
|
|
|
} else {
|
|
|
sidebar = 'hidden';
|
|
|
sidebar_toggle.checked = false;
|
|
|
}
|
|
|
if (sidebar === 'visible') {
|
|
|
sidebar_toggle.checked = true;
|
|
|
} else {
|
|
|
html.classList.remove('sidebar-visible');
|
|
|
}
|
|
|
</script>
|
|
|
|
|
|
<nav id="mdbook-sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
<!-- populated by js -->
|
|
|
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
|
|
|
<noscript>
|
|
|
<iframe class="sidebar-iframe-outer" src="../toc.html"></iframe>
|
|
|
</noscript>
|
|
|
<div id="mdbook-sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
</div>
|
|
|
</nav>
|
|
|
|
|
|
<div id="mdbook-page-wrapper" class="page-wrapper">
|
|
|
|
|
|
<div class="page">
|
|
|
<div id="mdbook-menu-bar-hover-placeholder"></div>
|
|
|
<div id="mdbook-menu-bar" class="menu-bar sticky">
|
|
|
<div class="left-buttons">
|
|
|
<label id="mdbook-sidebar-toggle" class="icon-button" for="mdbook-sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="mdbook-sidebar">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z"/></svg></span>
|
|
|
</label>
|
|
|
<button id="mdbook-theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="mdbook-theme-list">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z"/></svg></span>
|
|
|
</button>
|
|
|
<ul id="mdbook-theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-default_theme">Auto</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-light">Light</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-rust">Rust</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-coal">Coal</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-navy">Navy</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-ayu">Ayu</button></li>
|
|
|
</ul>
|
|
|
<button id="mdbook-search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="mdbook-searchbar">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z"/></svg></span>
|
|
|
</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">
|
|
|
<span class=fa-svg id="print-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z"/></svg></span>
|
|
|
</a>
|
|
|
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span>
|
|
|
</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" rel="edit">
|
|
|
<span class=fa-svg id="git-edit-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M421.7 220.3l-11.3 11.3-22.6 22.6-205 205c-6.6 6.6-14.8 11.5-23.8 14.1L30.8 511c-8.4 2.5-17.5 .2-23.7-6.1S-1.5 489.7 1 481.2L38.7 353.1c2.6-9 7.5-17.2 14.1-23.8l205-205 22.6-22.6 11.3-11.3 33.9 33.9 62.1 62.1 33.9 33.9zM96 353.9l-9.3 9.3c-.9 .9-1.6 2.1-2 3.4l-25.3 86 86-25.3c1.3-.4 2.5-1.1 3.4-2l9.3-9.3H112c-8.8 0-16-7.2-16-16V353.9zM453.3 19.3l39.4 39.4c25 25 25 65.5 0 90.5l-14.5 14.5-22.6 22.6-11.3 11.3-33.9-33.9-62.1-62.1L314.3 67.7l11.3-11.3 22.6-22.6 14.5-14.5c25-25 65.5-25 90.5 0z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
</div>
|
|
|
</div>
|
|
|
|
|
|
<div id="mdbook-search-wrapper" class="hidden">
|
|
|
<form id="mdbook-searchbar-outer" class="searchbar-outer">
|
|
|
<div class="search-wrapper">
|
|
|
<input type="search" id="mdbook-searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="mdbook-searchresults-outer" aria-describedby="searchresults-header">
|
|
|
<div class="spinner-wrapper">
|
|
|
<span class=fa-svg id="fa-spin"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z"/></svg></span>
|
|
|
</div>
|
|
|
</div>
|
|
|
</form>
|
|
|
<div id="mdbook-searchresults-outer" class="searchresults-outer hidden">
|
|
|
<div id="mdbook-searchresults-header" class="searchresults-header"></div>
|
|
|
<ul id="mdbook-searchresults">
|
|
|
</ul>
|
|
|
</div>
|
|
|
</div>
|
|
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
|
<script>
|
|
|
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
});
|
|
|
</script>
|
|
|
|
|
|
<div id="mdbook-content" class="content">
|
|
|
<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 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!("hello from async");
|
|
|
// 通过 .await 创建 socket 连接
|
|
|
let _socket = TcpStream::connect("127.0.0.1:3000").await.unwrap();
|
|
|
println!("async TCP operation complete");
|
|
|
// 关闭socket
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>接着对它进行调用获取一个返回值,再在返回值上调用 <code>.await</code>:</p>
|
|
|
<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>
|
|
|
<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 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<&mut Self>, cx: &mut Context)
|
|
|
-> Poll<Self::Output>;
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>代码中有几个关键点:</p>
|
|
|
<ul>
|
|
|
<li><a href="https://course.rs/basic/trait/advance-trait.html#关联类型">关联类型</a> <code>Output</code> 是 <code>Future</code> 执行完成后返回的值的类型</li>
|
|
|
<li><code>Pin</code> 类型是在异步函数中进行借用的关键,在<a href="https://course.rs/advance/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 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 = &'static str;
|
|
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
|
|
|
-> Poll<&'static str>
|
|
|
{
|
|
|
if Instant::now() >= self.when {
|
|
|
// 时间到了,Future 可以结束
|
|
|
println!("Hello world");
|
|
|
// Future 执行结束并返回 "done" 字符串
|
|
|
Poll::Ready("done")
|
|
|
} 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 返回的字符串是否是 "done"
|
|
|
assert_eq!(out, "done");
|
|
|
}</code></pre>
|
|
|
<p>以上代码很清晰的解释了如何自定义一个 <code>Future</code>,并指定它如何通过 <code>poll</code> 一步一步执行,直到最终完成返回 <code>"done"</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 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<&mut Self>, cx: &mut Context<'_>)
|
|
|
-> Poll<()>
|
|
|
{
|
|
|
use MainFuture::*;
|
|
|
|
|
|
loop {
|
|
|
match *self {
|
|
|
State0 => {
|
|
|
let when = Instant::now() +
|
|
|
Duration::from_millis(10);
|
|
|
let future = Delay { when };
|
|
|
*self = State1(future);
|
|
|
}
|
|
|
State1(ref mut my_future) => {
|
|
|
match Pin::new(my_future).poll(cx) {
|
|
|
Poll::Ready(out) => {
|
|
|
assert_eq!(out, "done");
|
|
|
*self = Terminated;
|
|
|
return Poll::Ready(());
|
|
|
}
|
|
|
Poll::Pending => {
|
|
|
return Poll::Pending;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
Terminated => {
|
|
|
panic!("future polled after completion")
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">}</span></code></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 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, "done");
|
|
|
});
|
|
|
|
|
|
mini_tokio.run();
|
|
|
}
|
|
|
|
|
|
struct MiniTokio {
|
|
|
tasks: VecDeque<Task>,
|
|
|
}
|
|
|
|
|
|
type Task = Pin<Box<dyn Future<Output = ()> + Send>>;
|
|
|
|
|
|
impl MiniTokio {
|
|
|
fn new() -> MiniTokio {
|
|
|
MiniTokio {
|
|
|
tasks: VecDeque::new(),
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// 生成一个 Future并放入 mini-tokio 实例的任务队列中
|
|
|
fn spawn<F>(&mut self, future: F)
|
|
|
where
|
|
|
F: Future<Output = ()> + Send + 'static,
|
|
|
{
|
|
|
self.tasks.push_back(Box::pin(future));
|
|
|
}
|
|
|
|
|
|
fn run(&mut self) {
|
|
|
let waker = task::noop_waker();
|
|
|
let mut cx = Context::from_waker(&waker);
|
|
|
|
|
|
while let Some(mut task) = self.tasks.pop_front() {
|
|
|
if task.as_mut().poll(&mut cx).is_pending() {
|
|
|
self.tasks.push_back(task);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}</code></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>通知 -> 运行</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 class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span>fn poll(self: Pin<&mut Self>, cx: &mut Context)
|
|
|
-> Poll<Self::Output>;
|
|
|
<span class="boring">}</span></code></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 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 = &'static str;
|
|
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
|
|
|
-> Poll<&'static str>
|
|
|
{
|
|
|
if Instant::now() >= self.when {
|
|
|
println!("Hello world");
|
|
|
Poll::Ready("done")
|
|
|
} else {
|
|
|
// 为当前任务克隆一个 waker 的句柄
|
|
|
let waker = cx.waker().clone();
|
|
|
let when = self.when;
|
|
|
|
|
|
// 生成一个计时器线程
|
|
|
thread::spawn(move || {
|
|
|
let now = Instant::now();
|
|
|
|
|
|
if now < when {
|
|
|
thread::sleep(when - now);
|
|
|
}
|
|
|
|
|
|
waker.wake();
|
|
|
});
|
|
|
|
|
|
Poll::Pending
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">}</span></code></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 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 = &'static str;
|
|
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
|
|
|
-> Poll<&'static str>
|
|
|
{
|
|
|
if Instant::now() >= self.when {
|
|
|
// 时间到了,Future 可以结束
|
|
|
println!("Hello world");
|
|
|
// Future 执行结束并返回 "done" 字符串
|
|
|
Poll::Ready("done")
|
|
|
} else {
|
|
|
// 目前先忽略下面这行代码
|
|
|
cx.waker().wake_by_ref();
|
|
|
Poll::Pending
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">}</span></code></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>执行 -> 立即通知再调度 -> 执行</code> 的方式会造成一个非常繁忙的循环。</p>
|
|
|
<h4 id="处理-wake-通知"><a class="header" href="#处理-wake-通知">处理 wake 通知</a></h4>
|
|
|
<p>下面,让我们更新 mini-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>std::sync::mpsc</code> 重新实现 <code>MiniTokio</code> 结构体:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span>use std::sync::mpsc;
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
struct MiniTokio {
|
|
|
scheduled: mpsc::Receiver<Arc<Task>>,
|
|
|
sender: mpsc::Sender<Arc<Task>>,
|
|
|
}
|
|
|
|
|
|
struct Task {
|
|
|
// 先空着,后面会填充代码
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p><code>Waker</code> 实现了 <code>Sync</code> 特征,同时还可以被克隆,当 <code>wake</code> 被调用时,任务就会被调度执行。</p>
|
|
|
<p>为了实现上述的目的,我们引入了消息通道,当 <code>waker.wake()</code> 函数被调用时,任务会被发送到该消息通道中:</p>
|
|
|
<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<Pin<Box<dyn Future<Output = ()> + Send>>>,
|
|
|
executor: mpsc::Sender<Arc<Task>>,
|
|
|
}
|
|
|
|
|
|
impl Task {
|
|
|
fn schedule(self: &Arc<Self>) {
|
|
|
self.executor.send(self.clone());
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">}</span></code></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 = "0.3"
|
|
|
</code></pre>
|
|
|
<p>然后为我们的任务 <code>Task</code> 实现 <code>ArcWake</code>:</p>
|
|
|
<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: &Arc<Self>) {
|
|
|
arc_self.schedule();
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>当之前的计时器线程调用 <code>waker.wake()</code> 时,所在的任务会被推入到消息通道中。因此接下来,我们需要实现接收端的功能,然后 <code>MiniTokio::run()</code> 函数中执行该任务:</p>
|
|
|
<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(&self) {
|
|
|
while let Ok(task) = self.scheduled.recv() {
|
|
|
task.poll();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/// 初始化一个新的 mini-tokio 实例
|
|
|
fn new() -> MiniTokio {
|
|
|
let (sender, scheduled) = mpsc::channel();
|
|
|
|
|
|
MiniTokio { scheduled, sender }
|
|
|
}
|
|
|
|
|
|
|
|
|
/// 在下面函数中,通过参数传入的 future 被 `Task` 包裹起来,然后会被推入到调度队列中,当 `run` 被调用时,该 future 将被执行
|
|
|
fn spawn<F>(&self, future: F)
|
|
|
where
|
|
|
F: Future<Output = ()> + Send + 'static,
|
|
|
{
|
|
|
Task::spawn(future, &self.sender);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
impl Task {
|
|
|
fn poll(self: Arc<Self>) {
|
|
|
// 基于 Task 实例创建一个 waker, 它使用了之前的 `ArcWake`
|
|
|
let waker = task::waker(self.clone());
|
|
|
let mut cx = Context::from_waker(&waker);
|
|
|
|
|
|
// 没有其他线程在竞争锁时,我们将获取到目标 future
|
|
|
let mut future = self.future.try_lock().unwrap();
|
|
|
|
|
|
// 对 future 进行 poll
|
|
|
let _ = future.as_mut().poll(&mut cx);
|
|
|
}
|
|
|
|
|
|
// 使用给定的 future 来生成新的任务
|
|
|
//
|
|
|
// 新的任务会被推到 `sender` 中,接着该消息通道的接收端就可以获取该任务,然后执行
|
|
|
fn spawn<F>(future: F, sender: &mpsc::Sender<Arc<Task>>)
|
|
|
where
|
|
|
F: Future<Output = ()> + 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>
|
|
|
<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 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(&mut delay).poll(cx);
|
|
|
assert!(res.is_pending());
|
|
|
tokio::spawn(async move {
|
|
|
delay.await;
|
|
|
});
|
|
|
|
|
|
Poll::Ready(())
|
|
|
}).await;
|
|
|
}</code></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 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<Arc<Mutex<Waker>>>,
|
|
|
}
|
|
|
|
|
|
impl Future for Delay {
|
|
|
type Output = ();
|
|
|
|
|
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
|
|
|
// 若这是 Future 第一次被调用,那么需要先生成一个计时器线程。
|
|
|
// 若不是第一次调用(该线程已在运行),那要确保已存储的 `Waker` 跟当前任务的 `waker` 匹配
|
|
|
if let Some(waker) = &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 < when {
|
|
|
thread::sleep(when - now);
|
|
|
}
|
|
|
|
|
|
// 计时结束,通过调用 `waker` 来通知执行器
|
|
|
let waker = waker.lock().unwrap();
|
|
|
waker.wake_by_ref();
|
|
|
});
|
|
|
}
|
|
|
|
|
|
// 一旦 waker 被存储且计时器线程已经开始,我们就需要检查 `delay` 是否已经完成
|
|
|
// 若计时已完成,则当前 Future 就可以完成并返回 `Poll::Ready`
|
|
|
if Instant::now() >= self.when {
|
|
|
Poll::Ready(())
|
|
|
} else {
|
|
|
// 计时尚未结束,Future 还未完成,因此返回 `Poll::Pending`.
|
|
|
//
|
|
|
// `Future` 特征要求当 `Pending` 被返回时,那我们要确保当资源准备好时,必须调用 `waker` 以通
|
|
|
// 知执行器。 在我们的例子中,会通过生成的计时线程来保证
|
|
|
//
|
|
|
// 如果忘记调用 waker, 那等待我们的将是深渊:该任务将被永远的挂起,无法再执行
|
|
|
Poll::Pending
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">}</span></code></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 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 < when {
|
|
|
thread::sleep(when - now);
|
|
|
}
|
|
|
|
|
|
notify2.notify_one();
|
|
|
});
|
|
|
|
|
|
|
|
|
notify.notified().await;
|
|
|
}
|
|
|
<span class="boring">}</span></code></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>
|
|
|
|
|
|
</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">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
<a rel="next prefetch" href="../advance-practice/select.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
|
|
</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">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
<a rel="next prefetch" href="../advance-practice/select.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
|
|
</a>
|
|
|
</nav>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<template id=fa-eye><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z"/></svg></span></template>
|
|
|
<template id=fa-eye-slash><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z"/></svg></span></template>
|
|
|
<template id=fa-copy><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg></span></template>
|
|
|
<template id=fa-play><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"/></svg></span></template>
|
|
|
<template id=fa-clock-rotate-left><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z"/></svg></span></template>
|
|
|
|
|
|
|
|
|
|
|
|
<script>
|
|
|
window.playground_copyable = true;
|
|
|
</script>
|
|
|
|
|
|
<script src="../ace-2a3cd908.js"></script>
|
|
|
<script src="../mode-rust-2c9d5c9a.js"></script>
|
|
|
<script src="../editor-16ca416c.js"></script>
|
|
|
<script src="../theme-dawn-4493f9c8.js"></script>
|
|
|
<script src="../theme-tomorrow_night-9dbe62a9.js"></script>
|
|
|
|
|
|
<script src="../elasticlunr-ef4e11c1.min.js"></script>
|
|
|
<script src="../mark-09e88c2c.min.js"></script>
|
|
|
<script src="../searcher-c2a407aa.js"></script>
|
|
|
|
|
|
<script src="../clipboard-1626706a.min.js"></script>
|
|
|
<script src="../highlight-abc7f01d.js"></script>
|
|
|
<script src="../book-a0b12cfe.js"></script>
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
<script src="../assets/custom-7d8ae1df.js"></script>
|
|
|
<script src="../assets/bigPicture-be03f9c8.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
</body>
|
|
|
</html>
|