|
|
<!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/async/getting-started.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="async-编程简介"><a class="header" href="#async-编程简介">Async 编程简介</a></h1>
|
|
|
<p>众所周知,Rust 可以让我们写出性能高且安全的软件,那么异步编程这块儿呢?是否依然在高性能的同时保证了安全?</p>
|
|
|
<p>我们先通过一张 web 框架性能对比图来感受下 Rust 异步编程的性能:</p>
|
|
|
<img alt="actix-vs-gin screenshot" width="100%" src="https://pic1.zhimg.com/v2-3cebd732fb56f43713f106fdcfa44a3c_b.png" class="center" />
|
|
|
<p>上图并不能说 Rust 写的 <code>actix</code> 框架比 Go 的 <code>gin</code> 更好、更优秀,但是确实可以一定程度上说明 Rust 的异步性能非常的高!</p>
|
|
|
<p>简单来说,异步编程是一个<a href="https://course.rs/advance/concurrency-with-threads/concurrency-parallelism.html">并发编程模型</a>,目前主流语言基本都支持了,当然,支持的方式有所不同。异步编程允许我们同时并发运行大量的任务,却仅仅需要几个甚至一个 OS 线程或 CPU 核心,现代化的异步编程在使用体验上跟同步编程也几无区别,例如 Go 语言的 <code>go</code> 关键字,也包括我们后面将介绍的 <code>async/await</code> 语法,该语法是 <code>JavaScript</code> 和 <code>Rust</code> 的核心特性之一。</p>
|
|
|
<h2 id="async-简介"><a class="header" href="#async-简介">async 简介</a></h2>
|
|
|
<p><code>async</code> 是 Rust 选择的异步编程模型,下面我们来介绍下它的优缺点,以及何时适合使用。</p>
|
|
|
<h4 id="async-vs-其它并发模型"><a class="header" href="#async-vs-其它并发模型">async vs 其它并发模型</a></h4>
|
|
|
<p>由于并发编程在现代社会非常重要,因此每个主流语言都对自己的并发模型进行过权衡取舍和精心设计,Rust 语言也不例外。下面的列表可以帮助大家理解不同并发模型的取舍:</p>
|
|
|
<ul>
|
|
|
<li><strong>OS 线程</strong>, 它最简单,也无需改变任何编程模型(业务/代码逻辑),因此非常适合作为语言的原生并发模型,我们在<a href="https://course.rs/advance/concurrency-with-threads/concurrency-parallelism.html">多线程章节</a>也提到过,Rust 就选择了原生支持线程级的并发编程。但是,这种模型也有缺点,例如线程间的同步将变得更加困难,线程间的上下文切换损耗较大。使用线程池在一定程度上可以提升性能,但是对于 IO 密集的场景来说,线程池还是不够。</li>
|
|
|
<li><strong>事件驱动(Event driven)</strong>, 这个名词你可能比较陌生,如果说事件驱动常常跟回调( Callback )一起使用,相信大家就恍然大悟了。这种模型性能相当的好,但最大的问题就是存在回调地狱的风险:非线性的控制流和结果处理导致了数据流向和错误传播变得难以掌控,还会导致代码可维护性和可读性的大幅降低,大名鼎鼎的 <code>JavaScript</code> 曾经就存在回调地狱。</li>
|
|
|
<li><strong>协程(Coroutines)</strong> 可能是目前最火的并发模型,<code>Go</code> 语言的协程设计就非常优秀,这也是 <code>Go</code> 语言能够迅速火遍全球的杀手锏之一。协程跟线程类似,无需改变编程模型,同时,它也跟 <code>async</code> 类似,可以支持大量的任务并发运行。但协程抽象层次过高,导致用户无法接触到底层的细节,这对于系统编程语言和自定义异步运行时是难以接受的</li>
|
|
|
<li><strong>actor 模型</strong>是 erlang 的杀手锏之一,它将所有并发计算分割成一个一个单元,这些单元被称为 <code>actor</code> ,单元之间通过消息传递的方式进行通信和数据传递,跟分布式系统的设计理念非常相像。由于 <code>actor</code> 模型跟现实很贴近,因此它相对来说更容易实现,但是一旦遇到流控制、失败重试等场景时,就会变得不太好用</li>
|
|
|
<li><strong>async/await</strong>, 该模型性能高,还能支持底层编程,同时又像线程和协程那样无需过多的改变编程模型,但有得必有失,<code>async</code> 模型的问题就是内部实现机制过于复杂,对于用户来说,理解和使用起来也没有线程和协程简单,好在前者的复杂性开发者们已经帮我们封装好,而理解和使用起来不够简单,正是本章试图解决的问题。</li>
|
|
|
</ul>
|
|
|
<p>总之,Rust 经过权衡取舍后,最终选择了同时提供多线程编程和 async 编程:</p>
|
|
|
<ul>
|
|
|
<li>前者通过标准库实现,当你无需那么高的并发时,例如需要并行计算时,可以选择它,优点是线程内的代码执行效率更高、实现更直观更简单,这块内容已经在多线程章节进行过深入讲解,不再赘述</li>
|
|
|
<li>后者通过语言特性 + 标准库 + 三方库的方式实现,在你需要高并发、异步 <code>I/O</code> 时,选择它就对了</li>
|
|
|
</ul>
|
|
|
<h4 id="async-rust-vs-其它语言"><a class="header" href="#async-rust-vs-其它语言">async: Rust vs 其它语言</a></h4>
|
|
|
<p>目前已经有诸多语言都通过 <code>async</code> 的方式提供了异步编程,例如 <code>JavaScript</code> ,但 <code>Rust</code> 在实现上有所区别:</p>
|
|
|
<ul>
|
|
|
<li><strong>Future 在 Rust 中是惰性的</strong>,只有在被轮询(<code>poll</code>)时才会运行, 因此丢弃一个 <code>future</code> 会阻止它未来再被运行,你可以将<code>Future</code>理解为一个在未来某个时间点被调度执行的任务。</li>
|
|
|
<li><strong>Async 在 Rust 中使用开销是零</strong>, 意味着只有你能看到的代码(自己的代码)才有性能损耗,你看不到的(<code>async</code> 内部实现)都没有性能损耗,例如,你可以无需分配任何堆内存、也无需任何动态分发来使用 <code>async</code> ,这对于热点路径的性能有非常大的好处,正是得益于此,Rust 的异步编程性能才会这么高。</li>
|
|
|
<li><strong>Rust 没有内置异步调用所必需的运行时</strong>,但是无需担心,Rust 社区生态中已经提供了非常优异的运行时实现,例如大明星 <a href="https://tokio.rs"><code>tokio</code></a></li>
|
|
|
<li><strong>运行时同时支持单线程和多线程</strong>,这两者拥有各自的优缺点,稍后会讲</li>
|
|
|
</ul>
|
|
|
<h4 id="rust-async-vs-多线程"><a class="header" href="#rust-async-vs-多线程">Rust: async vs 多线程</a></h4>
|
|
|
<p>虽然 <code>async</code> 和多线程都可以实现并发编程,后者甚至还能通过线程池来增强并发能力,但是这两个方式并不互通,从一个方式切换成另一个需要大量的代码重构工作,因此提前为自己的项目选择适合的并发模型就变得至关重要。</p>
|
|
|
<p><code>OS</code> 线程非常适合少量任务并发,因为线程的创建和上下文切换是非常昂贵的,甚至于空闲的线程都会消耗系统资源。虽说线程池可以有效的降低性能损耗,但是也无法彻底解决问题。当然,线程模型也有其优点,例如它不会破坏你的代码逻辑和编程模型,你之前的顺序代码,经过少量修改适配后依然可以在新线程中直接运行,同时在某些操作系统中,你还可以改变线程的优先级,这对于实现驱动程序或延迟敏感的应用(例如硬实时系统)很有帮助。</p>
|
|
|
<p>对于长时间运行的 CPU 密集型任务,例如并行计算,使用线程将更有优势。 这种密集任务往往会让所在的线程持续运行,任何不必要的线程切换都会带来性能损耗,因此高并发反而在此时成为了一种多余。同时你所创建的线程数应该等于 CPU 核心数,充分利用 CPU 的并行能力,甚至还可以将线程绑定到 CPU 核心上,进一步减少线程上下文切换。</p>
|
|
|
<p>而高并发更适合 <code>IO</code> 密集型任务,例如 web 服务器、数据库连接等等网络服务,因为这些任务绝大部分时间都处于等待状态,如果使用多线程,那线程大量时间会处于无所事事的状态,再加上线程上下文切换的高昂代价,让多线程做 <code>IO</code> 密集任务变成了一件非常奢侈的事。而使用<code>async</code>,既可以有效的降低 <code>CPU</code> 和内存的负担,又可以让大量的任务并发的运行,一个任务一旦处于<code>IO</code>或者其他等待(阻塞)状态,就会被立刻切走并执行另一个任务,而这里的任务切换的性能开销要远远低于使用多线程时的线程上下文切换。</p>
|
|
|
<p>事实上, <code>async</code> 底层也是基于线程实现,但是它基于线程封装了一个运行时,可以将多个任务映射到少量线程上,然后将线程切换变成了任务切换,后者仅仅是内存中的访问,因此要高效的多。</p>
|
|
|
<p>不过<code>async</code>也有其缺点,原因是编译器会为<code>async</code>函数生成状态机,然后将整个运行时打包进来,这会造成我们编译出的二进制可执行文件体积显著增大。</p>
|
|
|
<p>总之,<code>async</code>编程并没有比多线程更好,最终还是根据你的使用场景作出合适的选择,如果无需高并发,或者也不在意线程切换带来的性能损耗,那么多线程使用起来会简单、方便的多!最后再简单总结下:</p>
|
|
|
<blockquote>
|
|
|
<p>若大家使用 tokio,那 CPU 密集的任务尤其需要用线程的方式去处理,例如使用 <code>spawn_blocking</code> 创建一个阻塞的线程去完成相应 CPU 密集任务。</p>
|
|
|
<p>至于具体的原因,不仅是上文说到的那些,还有一个是:tokio 是协作式的调度器,如果某个 CPU 密集的异步任务是通过 tokio 创建的,那理论上来说,该异步任务需要跟其它的异步任务交错执行,最终大家都得到了执行,皆大欢喜。但实际情况是,CPU 密集的任务很可能会一直霸占着 CPU,此时 tokio 的调度方式决定了该任务会一直被执行,这意味着,其它的异步任务无法得到执行的机会,最终这些任务都会因为得不到资源而饿死。</p>
|
|
|
<p>而使用 <code>spawn_blocking</code> 后,会创建一个单独的 OS 线程,该线程并不会被 tokio 所调度( 被 OS 所调度 ),因此它所执行的 CPU 密集任务也不会导致 tokio 调度的那些异步任务被饿死</p>
|
|
|
</blockquote>
|
|
|
<ul>
|
|
|
<li>有大量 <code>IO</code> 任务需要并发运行时,选 <code>async</code> 模型</li>
|
|
|
<li>有部分 <code>IO</code> 任务需要并发运行时,选多线程,如果想要降低线程创建和销毁的开销,可以使用线程池</li>
|
|
|
<li>有大量 <code>CPU</code> 密集任务需要并行运行时,例如并行计算,选多线程模型,且让线程数等于或者稍大于 <code>CPU</code> 核心数</li>
|
|
|
<li>无所谓时,统一选多线程</li>
|
|
|
</ul>
|
|
|
<h4 id="async-和多线程的性能对比"><a class="header" href="#async-和多线程的性能对比">async 和多线程的性能对比</a></h4>
|
|
|
<div class="table-wrapper">
|
|
|
<table>
|
|
|
<thead>
|
|
|
<tr><th>操作</th><th>async</th><th>线程</th></tr>
|
|
|
</thead>
|
|
|
<tbody>
|
|
|
<tr><td>创建</td><td>0.3 微秒</td><td>17 微秒</td></tr>
|
|
|
<tr><td>线程切换</td><td>0.2 微秒</td><td>1.7 微秒</td></tr>
|
|
|
</tbody>
|
|
|
</table>
|
|
|
</div>
|
|
|
<p>可以看出,<code>async</code> 在线程切换的开销显著低于多线程,对于 IO 密集的场景,这种性能开销累计下来会非常可怕!</p>
|
|
|
<h4 id="一个例子"><a class="header" href="#一个例子">一个例子</a></h4>
|
|
|
<p>在大概理解<code>async</code>后,我们再来看一个简单的例子。如果想并发的下载文件,你可以使用多线程如下实现:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span>fn get_two_sites() {
|
|
|
// 创建两个新线程执行任务
|
|
|
let thread_one = thread::spawn(|| download("https://course.rs"));
|
|
|
let thread_two = thread::spawn(|| download("https://fancy.rs"));
|
|
|
|
|
|
// 等待两个线程的完成
|
|
|
thread_one.join().expect("thread one panicked");
|
|
|
thread_two.join().expect("thread two panicked");
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>如果是在一个小项目中简单的去下载文件,这么写没有任何问题,但是一旦下载文件的并发请求多起来,那一个下载任务占用一个线程的模式就太重了,会很容易成为程序的瓶颈。好在,我们可以使用<code>async</code>的方式来解决:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span>async fn get_two_sites_async() {
|
|
|
// 创建两个不同的`future`,你可以把`future`理解为未来某个时刻会被执行的计划任务
|
|
|
// 当两个`future`被同时执行后,它们将并发的去下载目标页面
|
|
|
let future_one = download_async("https://www.foo.com");
|
|
|
let future_two = download_async("https://www.bar.com");
|
|
|
|
|
|
// 同时运行两个`future`,直至完成
|
|
|
join!(future_one, future_two);
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>此时,不再有线程创建和切换的昂贵开销,所有的函数都是通过静态的方式进行分发,同时也没有任何内存分配发生。这段代码的性能简直无懈可击!</p>
|
|
|
<p>事实上,<code>async</code> 和多线程并不是二选一,在同一应用中,可以根据情况两者一起使用,当然,我们还可以使用其它的并发模型,例如上面提到事件驱动模型,前提是有三方库提供了相应的实现。</p>
|
|
|
<h2 id="async-rust-当前的进展"><a class="header" href="#async-rust-当前的进展">Async Rust 当前的进展</a></h2>
|
|
|
<p>简而言之,Rust 语言的 <code>async</code> 目前还没有达到多线程的成熟度,其中一部分内容还在不断进化中,当然,这并不影响我们在生产级项目中使用,因为社区中还有 <code>tokio</code> 这种大杀器。</p>
|
|
|
<p>使用 <code>async</code> 时,你会遇到好的,也会遇到不好的,例如:</p>
|
|
|
<ul>
|
|
|
<li>收获卓越的性能</li>
|
|
|
<li>会经常跟进阶语言特性打交道,例如生命周期等,这些家伙可不好对付</li>
|
|
|
<li>一些兼容性问题,例如同步和异步代码、不同的异步运行时( <code>tokio</code> 与 <code>async-std</code> )</li>
|
|
|
<li>更昂贵的维护成本,原因是 <code>async</code> 和社区开发的运行时依然在不停的进化</li>
|
|
|
</ul>
|
|
|
<p>总之,<code>async</code> 在 Rust 中并不是一个善茬,你会遇到更多的困难或者说坑,也会带来更高的代码阅读成本及维护成本,但是为了性能,一切都值了,不是吗?</p>
|
|
|
<p>不过好在,这些进化早晚会彻底稳定成熟,而且在实际项目中,我们往往会使用成熟的三方库,例如<code>tokio</code>,因此可以避免一些类似的问题,但是对于本章的学习来说,<code>async</code> 的一些难点还是我们必须要去面对和征服的。</p>
|
|
|
<h4 id="语言和库的支持"><a class="header" href="#语言和库的支持">语言和库的支持</a></h4>
|
|
|
<p><code>async</code> 的底层实现非常复杂,且会导致编译后文件体积显著增加,因此 Rust 没有选择像 Go 语言那样内置了完整的特性和运行时,而是选择了通过 Rust 语言提供了必要的特性支持,再通过社区来提供 <code>async</code> 运行时的支持。 因此要完整的使用 <code>async</code> 异步编程,你需要依赖以下特性和外部库:</p>
|
|
|
<ul>
|
|
|
<li>所必须的特征(例如 <code>Future</code> )、类型和函数,由标准库提供实现</li>
|
|
|
<li>关键字 <code>async/await</code> 由 Rust 语言提供,并进行了编译器层面的支持</li>
|
|
|
<li>众多实用的类型、宏和函数由官方开发的 <a href="https://github.com/rust-lang/futures-rs"><code>futures</code></a> 包提供(不是标准库),它们可以用于任何 <code>async</code> 应用中。</li>
|
|
|
<li><code>async</code> 代码的执行、<code>IO</code> 操作、任务创建和调度等等复杂功能由社区的 <code>async</code> 运行时提供,例如 <a href="https://github.com/tokio-rs/tokio"><code>tokio</code></a> 和 <a href="https://github.com/async-rs/async-std"><code>async-std</code></a></li>
|
|
|
</ul>
|
|
|
<p>还有,你在同步( <code>synchronous</code> )代码中使用的一些语言特性在 <code>async</code> 中可能将无法再使用,而且 Rust 也不允许你在特征中声明 <code>async</code> 函数(可以通过三方库实现), 总之,你会遇到一些在同步代码中不会遇到的奇奇怪怪、形形色色的问题,不过不用担心,本章会专门用一个章节罗列这些问题,并给出相应的解决方案。</p>
|
|
|
<h4 id="编译和错误"><a class="header" href="#编译和错误">编译和错误</a></h4>
|
|
|
<p>在大多数情况下,<code>async</code> 中的编译错误和运行时错误跟之前没啥区别,但是依然有以下几点值得注意:</p>
|
|
|
<ul>
|
|
|
<li>编译错误,由于 <code>async</code> 编程时需要经常使用复杂的语言特性,例如生命周期和<code>Pin</code>,因此相关的错误可能会出现的更加频繁</li>
|
|
|
<li>运行时错误,编译器会为每一个<code>async</code>函数生成状态机,这会导致在栈跟踪时会包含这些状态机的细节,同时还包含了运行时对函数的调用,因此,栈跟踪记录(例如 <code>panic</code> 时)将变得更加难以解读</li>
|
|
|
<li>一些隐蔽的错误也可能发生,例如在一个 <code>async</code> 上下文中去调用一个阻塞的函数,或者没有正确的实现 <code>Future</code> 特征都有可能导致这种错误。这种错误可能会悄无声息的通过编译检查甚至有时候会通过单元测试。好在一旦你深入学习并掌握了本章的内容和 <code>async</code> 原理,可以有效的降低遇到这些错误的概率</li>
|
|
|
</ul>
|
|
|
<h4 id="兼容性考虑"><a class="header" href="#兼容性考虑">兼容性考虑</a></h4>
|
|
|
<p>异步代码和同步代码并不总能和睦共处。例如,我们无法在一个同步函数中去调用一个 <code>async</code> 异步函数,同步和异步代码也往往使用不同的设计模式,这些都会导致两者融合上的困难。</p>
|
|
|
<p>甚至于有时候,异步代码之间也存在类似的问题,如果一个库依赖于特定的 <code>async</code> 运行时来运行,那么这个库非常有必要告诉它的用户,它用了这个运行时。否则一旦用户选了不同的或不兼容的运行时,就会导致不可预知的麻烦。</p>
|
|
|
<h4 id="性能特性"><a class="header" href="#性能特性">性能特性</a></h4>
|
|
|
<p><code>async</code> 代码的性能主要取决于你使用的 <code>async</code> 运行时,好在这些运行时都经过了精心的设计,在你能遇到的绝大多数场景中,它们都能拥有非常棒的性能表现。</p>
|
|
|
<p>但是世事皆有例外。目前主流的 <code>async</code> 运行时几乎都使用了多线程实现,相比单线程虽然增加了并发表现,但是对于执行性能会有所损失,因为多线程实现会有同步和切换上的性能开销,若你需要极致的顺序执行性能,那么 <code>async</code> 目前并不是一个好的选择。</p>
|
|
|
<p>同样的,对于延迟敏感的任务来说,任务的执行次序需要能被严格掌控,而不是交由运行时去自动调度,后者会导致不可预知的延迟,例如一个 web 服务器总是有 <code>1%</code> 的请求,它们的延迟会远高于其它请求,因为调度过于繁忙导致了部分任务被延迟调度,最终导致了较高的延时。正因为此,这些延迟敏感的任务非常依赖于运行时或操作系统提供调度次序上的支持。</p>
|
|
|
<p>以上的两个需求,目前的 <code>async</code> 运行时并不能很好的支持,在未来可能会有更好的支持,但在此之前,我们可以尝试用多线程解决。</p>
|
|
|
<h2 id="asyncawait-简单入门"><a class="header" href="#asyncawait-简单入门">async/.await 简单入门</a></h2>
|
|
|
<p><code>async/.await</code> 是 Rust 内置的语言特性,可以让我们用同步的方式去编写异步的代码。</p>
|
|
|
<p>通过 <code>async</code> 标记的语法块会被转换成实现了<code>Future</code>特征的状态机。 与同步调用阻塞当前线程不同,当<code>Future</code>执行并遇到阻塞时,它会让出当前线程的控制权,这样其它的<code>Future</code>就可以在该线程中运行,这种方式完全不会导致当前线程的阻塞。</p>
|
|
|
<p>下面我们来通过例子学习 <code>async/.await</code> 关键字该如何使用,在开始之前,需要先引入 <code>futures</code> 包。编辑 <code>Cargo.toml</code> 文件并添加以下内容:</p>
|
|
|
<pre><code class="language-toml">[dependencies]
|
|
|
futures = "0.3"
|
|
|
</code></pre>
|
|
|
<h4 id="使用-async"><a class="header" href="#使用-async">使用 async</a></h4>
|
|
|
<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>async fn do_something() {
|
|
|
println!("go go go !");
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>需要注意,<strong>异步函数的返回值是一个 <code>Future</code></strong>,若直接调用该函数,不会输出任何结果,因为 <code>Future</code> 还未被执行:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
do_something();
|
|
|
}</code></pre>
|
|
|
<p>运行后,<code>go go go</code>并没有打印,同时编译器给予一个提示:<code>warning: unused implementer of Future that must be used</code>,告诉我们 <code>Future</code> 未被使用,那么到底该如何使用?答案是使用一个执行器( <code>executor</code> ):</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021">// `block_on`会阻塞当前线程直到指定的`Future`执行完成,这种阻塞当前线程以等待任务完成的方式较为简单、粗暴,
|
|
|
// 好在其它运行时的执行器(executor)会提供更加复杂的行为,例如将多个`future`调度到同一个线程上执行。
|
|
|
use futures::executor::block_on;
|
|
|
|
|
|
async fn hello_world() {
|
|
|
println!("hello, world!");
|
|
|
}
|
|
|
|
|
|
fn main() {
|
|
|
let future = hello_world(); // 返回一个Future, 因此不会打印任何输出
|
|
|
block_on(future); // 执行`Future`并等待其运行完成,此时"hello, world!"会被打印输出
|
|
|
}</code></pre>
|
|
|
<h4 id="使用await"><a class="header" href="#使用await">使用.await</a></h4>
|
|
|
<p>在上述代码的<code>main</code>函数中,我们使用<code>block_on</code>这个执行器等待<code>Future</code>的完成,让代码看上去非常像是同步代码,但是如果你要在一个<code>async fn</code>函数中去调用另一个<code>async fn</code>并等待其完成后再执行后续的代码,该如何做?例如:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021">use futures::executor::block_on;
|
|
|
|
|
|
async fn hello_world() {
|
|
|
hello_cat();
|
|
|
println!("hello, world!");
|
|
|
}
|
|
|
|
|
|
async fn hello_cat() {
|
|
|
println!("hello, kitty!");
|
|
|
}
|
|
|
fn main() {
|
|
|
let future = hello_world();
|
|
|
block_on(future);
|
|
|
}</code></pre>
|
|
|
<p>这里,我们在<code>hello_world</code>异步函数中先调用了另一个异步函数<code>hello_cat</code>,然后再输出<code>hello, world!</code>,看看运行结果:</p>
|
|
|
<pre><code class="language-console">warning: unused implementer of `futures::Future` that must be used
|
|
|
--> src/main.rs:6:5
|
|
|
|
|
|
|
6 | hello_cat();
|
|
|
| ^^^^^^^^^^^^
|
|
|
= note: futures do nothing unless you `.await` or poll them
|
|
|
...
|
|
|
hello, world!
|
|
|
</code></pre>
|
|
|
<p>不出所料,<code>main</code>函数中的<code>future</code>我们通过<code>block_on</code>函数进行了运行,但是这里的<code>hello_cat</code>返回的<code>Future</code>却没有任何人去执行它,不过好在编译器友善的给出了提示:<code>futures do nothing unless you `.await` or poll them</code>,两种解决方法:使用<code>.await</code>语法或者对<code>Future</code>进行轮询(<code>poll</code>)。</p>
|
|
|
<p>后者较为复杂,暂且不表,先来使用<code>.await</code>试试:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021">use futures::executor::block_on;
|
|
|
|
|
|
async fn hello_world() {
|
|
|
hello_cat().await;
|
|
|
println!("hello, world!");
|
|
|
}
|
|
|
|
|
|
async fn hello_cat() {
|
|
|
println!("hello, kitty!");
|
|
|
}
|
|
|
fn main() {
|
|
|
let future = hello_world();
|
|
|
block_on(future);
|
|
|
}</code></pre>
|
|
|
<p>为<code>hello_cat()</code>添加上<code>.await</code>后,结果立刻大为不同:</p>
|
|
|
<pre><code class="language-console">hello, kitty!
|
|
|
hello, world!
|
|
|
</code></pre>
|
|
|
<p>输出的顺序跟代码定义的顺序完全符合,因此,我们在上面代码中<strong>使用同步的代码顺序实现了异步的执行效果</strong>,非常简单、高效,而且很好理解,未来也绝对不会有回调地狱的发生。</p>
|
|
|
<p>总之,在<code>async fn</code>函数中使用<code>.await</code>可以等待另一个异步调用的完成。<strong>但是与<code>block_on</code>不同,<code>.await</code>并不会阻塞当前的线程</strong>,而是异步的等待<code>Future A</code>的完成,在等待的过程中,该线程还可以继续执行其它的<code>Future B</code>,最终实现了并发处理的效果。</p>
|
|
|
<h4 id="一个例子-1"><a class="header" href="#一个例子-1">一个例子</a></h4>
|
|
|
<p>考虑一个载歌载舞的例子,如果不用<code>.await</code>,我们可能会有如下实现:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021">use futures::executor::block_on;
|
|
|
|
|
|
struct Song {
|
|
|
author: String,
|
|
|
name: String,
|
|
|
}
|
|
|
|
|
|
async fn learn_song() -> Song {
|
|
|
Song {
|
|
|
author: "周杰伦".to_string(),
|
|
|
name: String::from("《菊花台》"),
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async fn sing_song(song: Song) {
|
|
|
println!(
|
|
|
"给大家献上一首{}的{} ~ {}",
|
|
|
song.author, song.name, "菊花残,满地伤~ ~"
|
|
|
);
|
|
|
}
|
|
|
|
|
|
async fn dance() {
|
|
|
println!("唱到情深处,身体不由自主的动了起来~ ~");
|
|
|
}
|
|
|
|
|
|
fn main() {
|
|
|
let song = block_on(learn_song());
|
|
|
block_on(sing_song(song));
|
|
|
block_on(dance());
|
|
|
}</code></pre>
|
|
|
<p>当然,以上代码运行结果无疑是正确的,但。。。它的性能何在?需要通过连续三次阻塞去等待三个任务的完成,一次只能做一件事,实际上我们完全可以载歌载舞啊:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2021">use futures::executor::block_on;
|
|
|
|
|
|
struct Song {
|
|
|
author: String,
|
|
|
name: String,
|
|
|
}
|
|
|
|
|
|
async fn learn_song() -> Song {
|
|
|
Song {
|
|
|
author: "曲婉婷".to_string(),
|
|
|
name: String::from("《我的歌声里》"),
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async fn sing_song(song: Song) {
|
|
|
println!(
|
|
|
"给大家献上一首{}的{} ~ {}",
|
|
|
song.author, song.name, "你存在我深深的脑海里~ ~"
|
|
|
);
|
|
|
}
|
|
|
|
|
|
async fn dance() {
|
|
|
println!("唱到情深处,身体不由自主的动了起来~ ~");
|
|
|
}
|
|
|
|
|
|
async fn learn_and_sing() {
|
|
|
// 这里使用`.await`来等待学歌的完成,但是并不会阻塞当前线程,该线程在学歌的任务`.await`后,完全可以去执行跳舞的任务
|
|
|
let song = learn_song().await;
|
|
|
|
|
|
// 唱歌必须要在学歌之后
|
|
|
sing_song(song).await;
|
|
|
}
|
|
|
|
|
|
async fn async_main() {
|
|
|
let f1 = learn_and_sing();
|
|
|
let f2 = dance();
|
|
|
|
|
|
// `join!`可以并发的处理和等待多个`Future`,若`learn_and_sing Future`被阻塞,那`dance Future`可以拿过线程的所有权继续执行。若`dance`也变成阻塞状态,那`learn_and_sing`又可以再次拿回线程所有权,继续执行。
|
|
|
// 若两个都被阻塞,那么`async main`会变成阻塞状态,然后让出线程所有权,并将其交给`main`函数中的`block_on`执行器
|
|
|
futures::join!(f1, f2);
|
|
|
}
|
|
|
|
|
|
fn main() {
|
|
|
block_on(async_main());
|
|
|
}</code></pre>
|
|
|
<p>上面代码中,学歌和唱歌具有明显的先后顺序,但是这两者都可以跟跳舞一同存在,也就是你可以在跳舞的时候学歌,也可以在跳舞的时候唱歌。如果上面代码不使用<code>.await</code>,而是使用<code>block_on(learn_song())</code>, 那在学歌时,当前线程就会阻塞,不再可以做其它任何事,包括跳舞。</p>
|
|
|
<p>因此<code>.await</code>对于实现异步编程至关重要,它允许我们在同一个线程内并发的运行多个任务,而不是一个一个先后完成。若大家看到这里还是不太明白,强烈建议回头再仔细看一遍,同时亲自上手修改代码试试效果。</p>
|
|
|
<p>至此,读者应该对 Rust 的<code>async/.await</code>异步编程有了一个清晰的初步印象,下面让我们一起来看看这背后的原理:<code>Future</code>和任务在底层如何被执行。</p>
|
|
|
|
|
|
</main>
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
<a rel="prev" href="../../advance/async/intro.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/async/future-excuting.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/async/intro.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/async/future-excuting.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>
|