|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>async/await 和 Stream 流处理 - 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.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 class="sidebar-visible no-js">
|
|
|
|
|
<div id="body-container">
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script>
|
|
|
|
|
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>
|
|
|
|
|
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>
|
|
|
|
|
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('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
body.classList.remove('no-js')
|
|
|
|
|
body.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script>
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
var sidebar = null;
|
|
|
|
|
var sidebar_toggle = document.getElementById("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 = sidebar === 'visible';
|
|
|
|
|
body.classList.remove('sidebar-visible');
|
|
|
|
|
body.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="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Datav: 可编程的数据可视化平台和可观测性平台</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-contro
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
<!-- Track and set sidebar scroll position -->
|
|
|
|
|
<script>
|
|
|
|
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
|
|
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|
|
|
|
if (e.target.tagName === 'A') {
|
|
|
|
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
|
|
|
}
|
|
|
|
|
}, { passive: true });
|
|
|
|
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
|
|
|
sessionStorage.removeItem('sidebar-scroll');
|
|
|
|
|
if (sidebarScrollTop) {
|
|
|
|
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|
|
|
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
|
|
|
} else {
|
|
|
|
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
|
|
|
var activeSection = document.querySelector('#sidebar .active');
|
|
|
|
|
if (activeSection) {
|
|
|
|
|
activeSection.scrollIntoView({ block: 'center' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<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">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</label>
|
|
|
|
|
<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</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/async/async-await.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>
|
|
|
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
|
|
});
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="content" class="content">
|
|
|
|
|
<!-- Page table of contents -->
|
|
|
|
|
<div class="sidetoc"><nav class="pagetoc"></nav></div>
|
|
|
|
|
<main>
|
|
|
|
|
<h1 id="asyncawait-和-stream-流处理"><a class="header" href="#asyncawait-和-stream-流处理">async/await 和 Stream 流处理</a></h1>
|
|
|
|
|
<p>在入门章节中,我们简单学习了该如何使用 <code>async/.await</code>, 同时在后面也了解了一些底层原理,现在是时候继续深入了。</p>
|
|
|
|
|
<p><code>async/.await</code> 是 Rust 语法的一部分,它在遇到阻塞操作时( 例如 IO )会让出当前线程的所有权而不是阻塞当前线程,这样就允许当前线程继续去执行其它代码,最终实现并发。</p>
|
|
|
|
|
<p>有两种方式可以使用 <code>async</code>: <code>async fn</code> 用于声明函数,<code>async { ... }</code> 用于声明语句块,它们会返回一个实现 <code>Future</code> 特征的值:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>// `foo()`返回一个`Future<Output = u8>`,
|
|
|
|
|
// 当调用`foo().await`时,该`Future`将被运行,当调用结束后我们将获取到一个`u8`值
|
|
|
|
|
async fn foo() -> u8 { 5 }
|
|
|
|
|
|
|
|
|
|
fn bar() -> impl Future<Output = u8> {
|
|
|
|
|
// 下面的`async`语句块返回`Future<Output = u8>`
|
|
|
|
|
async {
|
|
|
|
|
let x: u8 = foo().await;
|
|
|
|
|
x + 5
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p><code>async</code> 是懒惰的,直到被执行器 <code>poll</code> 或者 <code>.await</code> 后才会开始运行,其中后者是最常用的运行 <code>Future</code> 的方法。 当 <code>.await</code> 被调用时,它会尝试运行 <code>Future</code> 直到完成,但是若该 <code>Future</code> 进入阻塞,那就会让出当前线程的控制权。当 <code>Future</code> 后面准备再一次被运行时(例如从 <code>socket</code> 中读取到了数据),执行器会得到通知,并再次运行该 <code>Future</code> ,如此循环,直到完成。</p>
|
|
|
|
|
<p>以上过程只是一个简述,详细内容在<a href="https://course.rs/advance/async/future-excuting.html">底层探秘</a>中已经被深入讲解过,因此这里不再赘述。</p>
|
|
|
|
|
<h2 id="async-的生命周期"><a class="header" href="#async-的生命周期"><code>async</code> 的生命周期</a></h2>
|
|
|
|
|
<p><code>async fn</code> 函数如果拥有引用类型的参数,那它返回的 <code>Future</code> 的生命周期就会被这些参数的生命周期所限制:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>async fn foo(x: &u8) -> u8 { *x }
|
|
|
|
|
|
|
|
|
|
// 上面的函数跟下面的函数是等价的:
|
|
|
|
|
fn foo_expanded<'a>(x: &'a u8) -> impl Future<Output = u8> + 'a {
|
|
|
|
|
async move { *x }
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>意味着 <code>async fn</code> 函数返回的 <code>Future</code> 必须满足以下条件: 当 <code>x</code> 依然有效时, 该 <code>Future</code> 就必须继续等待( <code>.await</code> ), 也就是说 <code>x</code> 必须比 <code>Future</code> 活得更久。</p>
|
|
|
|
|
<p>在一般情况下,在函数调用后就立即 <code>.await</code> 不会存在任何问题,例如<code>foo(&x).await</code>。但是,若 <code>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::future::Future;
|
|
|
|
|
fn bad() -> impl Future<Output = u8> {
|
|
|
|
|
let x = 5;
|
|
|
|
|
borrow_x(&x) // ERROR: `x` does not live long enough
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn borrow_x(x: &u8) -> u8 { *x }
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>以上代码会报错,因为 <code>x</code> 的生命周期只到 <code>bad</code> 函数的结尾。 但是 <code>Future</code> 显然会活得更久:</p>
|
|
|
|
|
<pre><code class="language-shell">error[E0597]: `x` does not live long enough
|
|
|
|
|
--> src/main.rs:4:14
|
|
|
|
|
|
|
|
|
|
|
4 | borrow_x(&x) // ERROR: `x` does not live long enough
|
|
|
|
|
| ---------^^-
|
|
|
|
|
| | |
|
|
|
|
|
| | borrowed value does not live long enough
|
|
|
|
|
| argument requires that `x` is borrowed for `'static`
|
|
|
|
|
5 | }
|
|
|
|
|
| - `x` dropped here while still borrowed
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>其中一个常用的解决方法就是将具有引用参数的 <code>async fn</code> 函数转变成一个具有 <code>'static</code> 生命周期的 <code>Future</code> 。 以上解决方法可以通过将参数和对 <code>async fn</code> 的调用放在同一个 <code>async</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;
|
|
|
|
|
|
|
|
|
|
async fn borrow_x(x: &u8) -> u8 { *x }
|
|
|
|
|
|
|
|
|
|
fn good() -> impl Future<Output = u8> {
|
|
|
|
|
async {
|
|
|
|
|
let x = 5;
|
|
|
|
|
borrow_x(&x).await
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>如上所示,通过将参数移动到 <code>async</code> 语句块内, 我们将它的生命周期扩展到 <code>'static</code>, 并跟返回的 <code>Future</code> 保持了一致。</p>
|
|
|
|
|
<h2 id="async-move"><a class="header" href="#async-move">async move</a></h2>
|
|
|
|
|
<p><code>async</code> 允许我们使用 <code>move</code> 关键字来将环境中变量的所有权转移到语句块内,就像闭包那样,好处是你不再发愁该如何解决借用生命周期的问题,坏处就是无法跟其它代码实现对变量的共享:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>// 多个不同的 `async` 语句块可以访问同一个本地变量,只要它们在该变量的作用域内执行
|
|
|
|
|
async fn blocks() {
|
|
|
|
|
let my_string = "foo".to_string();
|
|
|
|
|
|
|
|
|
|
let future_one = async {
|
|
|
|
|
// ...
|
|
|
|
|
println!("{my_string}");
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let future_two = async {
|
|
|
|
|
// ...
|
|
|
|
|
println!("{my_string}");
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 运行两个 Future 直到完成
|
|
|
|
|
let ((), ()) = futures::join!(future_one, future_two);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 由于 `async move` 会捕获环境中的变量,因此只有一个 `async move` 语句块可以访问该变量,
|
|
|
|
|
// 但是它也有非常明显的好处: 变量可以转移到返回的 Future 中,不再受借用生命周期的限制
|
|
|
|
|
fn move_block() -> impl Future<Output = ()> {
|
|
|
|
|
let my_string = "foo".to_string();
|
|
|
|
|
async move {
|
|
|
|
|
// ...
|
|
|
|
|
println!("{my_string}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<h2 id="当await-遇见多线程执行器"><a class="header" href="#当await-遇见多线程执行器">当.await 遇见多线程执行器</a></h2>
|
|
|
|
|
<p>需要注意的是,当使用多线程 <code>Future</code> 执行器( <code>executor</code> )时, <code>Future</code> 可能会在线程间被移动,因此 <code>async</code> 语句块中的变量必须要能在线程间传递。 至于 <code>Future</code> 会在线程间移动的原因是:它内部的任何<code>.await</code>都可能导致它被切换到一个新线程上去执行。</p>
|
|
|
|
|
<p>由于需要在多线程环境使用,意味着 <code>Rc</code>、 <code>RefCell</code> 、没有实现 <code>Send</code> 的所有权类型、没有实现 <code>Sync</code> 的引用类型,它们都是不安全的,因此无法被使用</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>需要注意!实际上它们还是有可能被使用的,只要在 <code>.await</code> 调用期间,它们没有在作用域范围内。</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>类似的原因,在 <code>.await</code> 时使用普通的锁也不安全,例如 <code>Mutex</code> 。原因是,它可能会导致线程池被锁:当一个任务获取锁 <code>A</code> 后,若它将线程的控制权还给执行器,然后执行器又调度运行另一个任务,该任务也去尝试获取了锁 <code>A</code> ,结果当前线程会直接卡死,最终陷入死锁中。</p>
|
|
|
|
|
<p>因此,为了避免这种情况的发生,我们需要使用 <code>futures</code> 包下的锁 <code>futures::lock</code> 来替代 <code>Mutex</code> 完成任务。</p>
|
|
|
|
|
<h2 id="stream-流处理"><a class="header" href="#stream-流处理">Stream 流处理</a></h2>
|
|
|
|
|
<p><code>Stream</code> 特征类似于 <code>Future</code> 特征,但是前者在完成前可以生成多个值,这种行为跟标准库中的 <code>Iterator</code> 特征倒是颇为相似。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>trait Stream {
|
|
|
|
|
// Stream生成的值的类型
|
|
|
|
|
type Item;
|
|
|
|
|
|
|
|
|
|
// 尝试去解析Stream中的下一个值,
|
|
|
|
|
// 若无数据,返回`Poll::Pending`, 若有数据,返回 `Poll::Ready(Some(x))`, `Stream`完成则返回 `Poll::Ready(None)`
|
|
|
|
|
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>)
|
|
|
|
|
-> Poll<Option<Self::Item>>;
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>关于 <code>Stream</code> 的一个常见例子是消息通道( <code>futures</code> 包中的)的消费者 <code>Receiver</code>。每次有消息从 <code>Send</code> 端发送后,它都可以接收到一个 <code>Some(val)</code> 值, 一旦 <code>Send</code> 端关闭( <code>drop</code> ),且消息通道中没有消息后,它会接收到一个 <code>None</code> 值。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>async fn send_recv() {
|
|
|
|
|
const BUFFER_SIZE: usize = 10;
|
|
|
|
|
let (mut tx, mut rx) = mpsc::channel::<i32>(BUFFER_SIZE);
|
|
|
|
|
|
|
|
|
|
tx.send(1).await.unwrap();
|
|
|
|
|
tx.send(2).await.unwrap();
|
|
|
|
|
drop(tx);
|
|
|
|
|
|
|
|
|
|
// `StreamExt::next` 类似于 `Iterator::next`, 但是前者返回的不是值,而是一个 `Future<Output = Option<T>>`,
|
|
|
|
|
// 因此还需要使用`.await`来获取具体的值
|
|
|
|
|
assert_eq!(Some(1), rx.next().await);
|
|
|
|
|
assert_eq!(Some(2), rx.next().await);
|
|
|
|
|
assert_eq!(None, rx.next().await);
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<h4 id="迭代和并发"><a class="header" href="#迭代和并发">迭代和并发</a></h4>
|
|
|
|
|
<p>跟迭代器类似,我们也可以迭代一个 <code>Stream</code>。 例如使用 <code>map</code>,<code>filter</code>,<code>fold</code> 方法,以及它们的<em>遇到错误提前返回</em>的版本: <code>try_map</code>,<code>try_filter</code>,<code>try_fold</code>。</p>
|
|
|
|
|
<p>但是跟迭代器又有所不同,<code>for</code> 循环无法在这里使用,但是命令式风格的循环<code>while let</code>是可以用的,同时还可以使用<code>next</code> 和 <code>try_next</code> 方法:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>async fn sum_with_next(mut stream: Pin<&mut dyn Stream<Item = i32>>) -> i32 {
|
|
|
|
|
use futures::stream::StreamExt; // 引入 next
|
|
|
|
|
let mut sum = 0;
|
|
|
|
|
while let Some(item) = stream.next().await {
|
|
|
|
|
sum += item;
|
|
|
|
|
}
|
|
|
|
|
sum
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn sum_with_try_next(
|
|
|
|
|
mut stream: Pin<&mut dyn Stream<Item = Result<i32, io::Error>>>,
|
|
|
|
|
) -> Result<i32, io::Error> {
|
|
|
|
|
use futures::stream::TryStreamExt; // 引入 try_next
|
|
|
|
|
let mut sum = 0;
|
|
|
|
|
while let Some(item) = stream.try_next().await? {
|
|
|
|
|
sum += item;
|
|
|
|
|
}
|
|
|
|
|
Ok(sum)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面代码是一次处理一个值的模式,但是需要注意的是:<strong>如果你选择一次处理一个值的模式,可能会造成无法并发,这就失去了异步编程的意义</strong>。 因此,如果可以的话我们还是要选择从一个 <code>Stream</code> 并发处理多个值的方式,通过 <code>for_each_concurrent</code> 或 <code>try_for_each_concurrent</code> 方法来实现:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>async fn jump_around(
|
|
|
|
|
mut stream: Pin<&mut dyn Stream<Item = Result<u8, io::Error>>>,
|
|
|
|
|
) -> Result<(), io::Error> {
|
|
|
|
|
use futures::stream::TryStreamExt; // 引入 `try_for_each_concurrent`
|
|
|
|
|
const MAX_CONCURRENT_JUMPERS: usize = 100;
|
|
|
|
|
|
|
|
|
|
stream.try_for_each_concurrent(MAX_CONCURRENT_JUMPERS, |num| async move {
|
|
|
|
|
jump_n_times(num).await?;
|
|
|
|
|
report_n_jumps(num).await?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}).await?;
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../advance/async/pin-unpin.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 prefetch" href="../../advance/async/multi-futures-simultaneous.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/async/pin-unpin.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 prefetch" href="../../advance/async/multi-futures-simultaneous.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>
|
|
|
|
|
window.playground_copyable = true;
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<script src="../../ace.js"></script>
|
|
|
|
|
<script src="../../editor.js"></script>
|
|
|
|
|
<script src="../../mode-rust.js"></script>
|
|
|
|
|
<script src="../../theme-dawn.js"></script>
|
|
|
|
|
<script src="../../theme-tomorrow_night.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../elasticlunr.min.js"></script>
|
|
|
|
|
<script src="../../mark.min.js"></script>
|
|
|
|
|
<script src="../../searcher.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../clipboard.min.js"></script>
|
|
|
|
|
<script src="../../highlight.js"></script>
|
|
|
|
|
<script src="../../book.js"></script>
|
|
|
|
|
|
|
|
|
|
<script type="text/javascript" charset="utf-8">
|
|
|
|
|
var pagePath = "advance/async/async-await.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|