|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>同时运行多个 Future - 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">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</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></l
|
|
|
|
|
</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/multi-futures-simultaneous.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="使用-join-和-select-同时运行多个-future"><a class="header" href="#使用-join-和-select-同时运行多个-future">使用 <code>join!</code> 和 <code>select!</code> 同时运行多个 Future</a></h1>
|
|
|
|
|
<p>招数单一,杀伤力惊人,说的就是 <code>.await</code> ,但是光用它,还真做不到一招鲜吃遍天。比如我们该如何同时运行多个任务,而不是使用 <code>.await</code> 慢悠悠地排队完成。</p>
|
|
|
|
|
<h2 id="join"><a class="header" href="#join">join!</a></h2>
|
|
|
|
|
<p><code>futures</code> 包中提供了很多实用的工具,其中一个就是 <code>join!</code> 宏, 它允许我们同时等待多个不同 <code>Future</code> 的完成,且可以并发地运行这些 <code>Future</code>。</p>
|
|
|
|
|
<p>先来看一个不是很给力的、使用<code>.await</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 enjoy_book_and_music() -> (Book, Music) {
|
|
|
|
|
let book = enjoy_book().await;
|
|
|
|
|
let music = enjoy_music().await;
|
|
|
|
|
(book, music)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>这段代码可以顺利运行,但是有一个很大的问题,就是必须先看完书后,才能听音乐。咱们以前,谁又不是那个摇头晃脑爱读书(耳朵里偷偷塞着耳机,听的正 high)的好学生呢?</p>
|
|
|
|
|
<p>要支持同时看书和听歌,有些人可能会凭空生成下面代码:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>// WRONG -- 别这么做
|
|
|
|
|
async fn enjoy_book_and_music() -> (Book, Music) {
|
|
|
|
|
let book_future = enjoy_book();
|
|
|
|
|
let music_future = enjoy_music();
|
|
|
|
|
(book_future.await, music_future.await)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>看上去像模像样,嗯,在某些语言中也许可以,但是 Rust 不行。因为在某些语言中,<code>Future</code>一旦创建就开始运行,等到返回的时候,基本就可以同时结束并返回了。 但是 Rust 中的 <code>Future</code> 是惰性的,直到调用 <code>.await</code> 时,才会开始运行。而那两个 <code>await</code> 由于在代码中有先后顺序,因此它们是顺序运行的。</p>
|
|
|
|
|
<p>为了正确的并发运行两个 <code>Future</code> , 我们来试试 <code>futures::join!</code> 宏:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use futures::join;
|
|
|
|
|
|
|
|
|
|
async fn enjoy_book_and_music() -> (Book, Music) {
|
|
|
|
|
let book_fut = enjoy_book();
|
|
|
|
|
let music_fut = enjoy_music();
|
|
|
|
|
join!(book_fut, music_fut)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p><code>Duang</code>,目标顺利达成。同时 <code>join!</code> 会返回一个元组,里面的值是对应的 <code>Future</code> 执行结束后输出的值。</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>如果希望同时运行一个数组里的多个异步任务,可以使用 <code>futures::future::join_all</code> 方法</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<h2 id="try_join"><a class="header" href="#try_join">try_join!</a></h2>
|
|
|
|
|
<p>由于 <code>join!</code> 必须等待它管理的所有 <code>Future</code> 完成后才能完成,如果你希望在某一个 <code>Future</code> 报错后就立即停止所有 <code>Future</code> 的执行,可以使用 <code>try_join!</code>,特别是当 <code>Future</code> 返回 <code>Result</code> 时:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use futures::try_join;
|
|
|
|
|
|
|
|
|
|
async fn get_book() -> Result<Book, String> { /* ... */ Ok(Book) }
|
|
|
|
|
async fn get_music() -> Result<Music, String> { /* ... */ Ok(Music) }
|
|
|
|
|
|
|
|
|
|
async fn get_book_and_music() -> Result<(Book, Music), String> {
|
|
|
|
|
let book_fut = get_book();
|
|
|
|
|
let music_fut = get_music();
|
|
|
|
|
try_join!(book_fut, music_fut)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>有一点需要注意,传给 <code>try_join!</code> 的所有 <code>Future</code> 都必须拥有相同的错误类型。如果错误类型不同,可以考虑使用来自 <code>futures::future::TryFutureExt</code> 模块的 <code>map_err</code> 和 <code>err_info</code> 方法将错误进行转换:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use futures::{
|
|
|
|
|
future::TryFutureExt,
|
|
|
|
|
try_join,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
async fn get_book() -> Result<Book, ()> { /* ... */ Ok(Book) }
|
|
|
|
|
async fn get_music() -> Result<Music, String> { /* ... */ Ok(Music) }
|
|
|
|
|
|
|
|
|
|
async fn get_book_and_music() -> Result<(Book, Music), String> {
|
|
|
|
|
let book_fut = get_book().map_err(|()| "Unable to get book".to_string());
|
|
|
|
|
let music_fut = get_music();
|
|
|
|
|
try_join!(book_fut, music_fut)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p><code>join!</code> 很好很强大,但是人无完人,J 无完 J, 它有一个很大的问题。</p>
|
|
|
|
|
<h2 id="select"><a class="header" href="#select">select!</a></h2>
|
|
|
|
|
<p><code>join!</code> 只有等所有 <code>Future</code> 结束后,才能集中处理结果,如果你想同时等待多个 <code>Future</code> ,且任何一个 <code>Future</code> 结束后,都可以立即被处理,可以考虑使用 <code>futures::select!</code>:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use futures::{
|
|
|
|
|
future::FutureExt, // for `.fuse()`
|
|
|
|
|
pin_mut,
|
|
|
|
|
select,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
async fn task_one() { /* ... */ }
|
|
|
|
|
async fn task_two() { /* ... */ }
|
|
|
|
|
|
|
|
|
|
async fn race_tasks() {
|
|
|
|
|
let t1 = task_one().fuse();
|
|
|
|
|
let t2 = task_two().fuse();
|
|
|
|
|
|
|
|
|
|
pin_mut!(t1, t2);
|
|
|
|
|
|
|
|
|
|
select! {
|
|
|
|
|
() = t1 => println!("任务1率先完成"),
|
|
|
|
|
() = t2 => println!("任务2率先完成"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面的代码会同时并发地运行 <code>t1</code> 和 <code>t2</code>, 无论两者哪个先完成,都会调用对应的 <code>println!</code> 打印相应的输出,然后函数结束且不会等待另一个任务的完成。</p>
|
|
|
|
|
<p>但是,在实际项目中,我们往往需要等待多个任务都完成后,再结束,像上面这种其中一个任务结束就立刻结束的场景着实不多。</p>
|
|
|
|
|
<h4 id="default-和-complete"><a class="header" href="#default-和-complete">default 和 complete</a></h4>
|
|
|
|
|
<p><code>select!</code>还支持 <code>default</code> 和 <code>complete</code> 分支:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>complete</code> 分支当所有的 <code>Future</code> 和 <code>Stream</code> 完成后才会被执行,它往往配合 <code>loop</code> 使用,<code>loop</code> 用于循环完成所有的 <code>Future</code></li>
|
|
|
|
|
<li><code>default</code> 分支,若没有任何 <code>Future</code> 或 <code>Stream</code> 处于 <code>Ready</code> 状态, 则该分支会被立即执行</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use futures::future;
|
|
|
|
|
use futures::select;
|
|
|
|
|
pub fn main() {
|
|
|
|
|
let mut a_fut = future::ready(4);
|
|
|
|
|
let mut b_fut = future::ready(6);
|
|
|
|
|
let mut total = 0;
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
|
select! {
|
|
|
|
|
a = a_fut => total += a,
|
|
|
|
|
b = b_fut => total += b,
|
|
|
|
|
complete => break,
|
|
|
|
|
default => panic!(), // 该分支永远不会运行,因为 `Future` 会先运行,然后是 `complete`
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(total, 10);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上代码 <code>default</code> 分支由于最后一个运行,而在它之前 <code>complete</code> 分支已经通过 <code>break</code> 跳出了循环,因此 <code>default</code> 永远不会被执行。</p>
|
|
|
|
|
<p>如果你希望 <code>default</code> 也有机会露下脸,可以将 <code>complete</code> 的 <code>break</code> 修改为其它的,例如 <code>println!("completed!")</code>,然后再观察下运行结果。</p>
|
|
|
|
|
<p>再回到 <code>select</code> 的第一个例子中,里面有一段代码长这样:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let t1 = task_one().fuse();
|
|
|
|
|
let t2 = task_two().fuse();
|
|
|
|
|
|
|
|
|
|
pin_mut!(t1, t2);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>当时没有展开讲,相信大家也有疑惑,下面我们来一起看看。</p>
|
|
|
|
|
<h4 id="跟-unpin-和-fusedfuture-进行交互"><a class="header" href="#跟-unpin-和-fusedfuture-进行交互">跟 <code>Unpin</code> 和 <code>FusedFuture</code> 进行交互</a></h4>
|
|
|
|
|
<p>首先,<code>.fuse()</code> 方法可以让 <code>Future</code> 实现 <code>FusedFuture</code> 特征, 而 <code>pin_mut!</code> 宏会为 <code>Future</code> 实现 <code>Unpin</code> 特征,这两个特征恰恰是使用 <code>select</code> 所必须的:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>Unpin</code>,由于 <code>select</code> 不会通过拿走所有权的方式使用 <code>Future</code>,而是通过可变引用的方式去使用,这样当 <code>select</code> 结束后,该 <code>Future</code> 若没有被完成,它的所有权还可以继续被其它代码使用。</li>
|
|
|
|
|
<li><code>FusedFuture</code> 的原因跟上面类似,当 <code>Future</code> 一旦完成后,那 <code>select</code> 就不能再对其进行轮询使用。<code>Fuse</code> 意味着熔断,相当于 <code>Future</code> 一旦完成,再次调用 <code>poll</code> 会直接返回 <code>Poll::Pending</code>。</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>只有实现了 <code>FusedFuture</code>,<code>select</code> 才能配合 <code>loop</code> 一起使用。假如没有实现,就算一个 <code>Future</code> 已经完成了,它依然会被 <code>select</code> 不停的轮询执行。</p>
|
|
|
|
|
<p><code>Stream</code> 稍有不同,它们使用的特征是 <code>FusedStream</code>。 通过 <code>.fuse()</code>(也可以手动实现)实现了该特征的 <code>Stream</code>,对其调用 <code>.next()</code> 或 <code>.try_next()</code> 方法可以获取实现了 <code>FusedFuture</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 futures::{
|
|
|
|
|
stream::{Stream, StreamExt, FusedStream},
|
|
|
|
|
select,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
async fn add_two_streams(
|
|
|
|
|
mut s1: impl Stream<Item = u8> + FusedStream + Unpin,
|
|
|
|
|
mut s2: impl Stream<Item = u8> + FusedStream + Unpin,
|
|
|
|
|
) -> u8 {
|
|
|
|
|
let mut total = 0;
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
|
let item = select! {
|
|
|
|
|
x = s1.next() => x,
|
|
|
|
|
x = s2.next() => x,
|
|
|
|
|
complete => break,
|
|
|
|
|
};
|
|
|
|
|
if let Some(next_num) = item {
|
|
|
|
|
total += next_num;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
total
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<h2 id="在-select-循环中并发"><a class="header" href="#在-select-循环中并发">在 select 循环中并发</a></h2>
|
|
|
|
|
<p>一个很实用但又鲜为人知的函数是 <code>Fuse::terminated()</code> ,可以使用它构建一个空的 <code>Future</code> ,空自然没啥用,但是如果它能在后面再被填充呢?</p>
|
|
|
|
|
<p>考虑以下场景:当你要在 <code>select</code> 循环中运行一个任务,但是该任务却是在 <code>select</code> 循环内部创建时,上面的函数就非常好用了。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use futures::{
|
|
|
|
|
future::{Fuse, FusedFuture, FutureExt},
|
|
|
|
|
stream::{FusedStream, Stream, StreamExt},
|
|
|
|
|
pin_mut,
|
|
|
|
|
select,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
async fn get_new_num() -> u8 { /* ... */ 5 }
|
|
|
|
|
|
|
|
|
|
async fn run_on_new_num(_: u8) { /* ... */ }
|
|
|
|
|
|
|
|
|
|
async fn run_loop(
|
|
|
|
|
mut interval_timer: impl Stream<Item = ()> + FusedStream + Unpin,
|
|
|
|
|
starting_num: u8,
|
|
|
|
|
) {
|
|
|
|
|
let run_on_new_num_fut = run_on_new_num(starting_num).fuse();
|
|
|
|
|
let get_new_num_fut = Fuse::terminated();
|
|
|
|
|
pin_mut!(run_on_new_num_fut, get_new_num_fut);
|
|
|
|
|
loop {
|
|
|
|
|
select! {
|
|
|
|
|
() = interval_timer.select_next_some() => {
|
|
|
|
|
// 定时器已结束,若`get_new_num_fut`没有在运行,就创建一个新的
|
|
|
|
|
if get_new_num_fut.is_terminated() {
|
|
|
|
|
get_new_num_fut.set(get_new_num().fuse());
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
new_num = get_new_num_fut => {
|
|
|
|
|
// 收到新的数字 -- 创建一个新的`run_on_new_num_fut`并丢弃掉旧的
|
|
|
|
|
run_on_new_num_fut.set(run_on_new_num(new_num).fuse());
|
|
|
|
|
},
|
|
|
|
|
// 运行 `run_on_new_num_fut`
|
|
|
|
|
() = run_on_new_num_fut => {},
|
|
|
|
|
// 若所有任务都完成,直接 `panic`, 原因是 `interval_timer` 应该连续不断的产生值,而不是结束
|
|
|
|
|
//后,执行到 `complete` 分支
|
|
|
|
|
complete => panic!("`interval_timer` completed unexpectedly"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>当某个 <code>Future</code> 有多个拷贝都需要同时运行时,可以使用 <code>FuturesUnordered</code> 类型。下面的例子跟上个例子大体相似,但是它会将 <code>run_on_new_num_fut</code> 的每一个拷贝都运行到完成,而不是像之前那样一旦创建新的就终止旧的。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use futures::{
|
|
|
|
|
future::{Fuse, FusedFuture, FutureExt},
|
|
|
|
|
stream::{FusedStream, FuturesUnordered, Stream, StreamExt},
|
|
|
|
|
pin_mut,
|
|
|
|
|
select,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
async fn get_new_num() -> u8 { /* ... */ 5 }
|
|
|
|
|
|
|
|
|
|
async fn run_on_new_num(_: u8) -> u8 { /* ... */ 5 }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 使用从 `get_new_num` 获取的最新数字 来运行 `run_on_new_num`
|
|
|
|
|
//
|
|
|
|
|
// 每当计时器结束后,`get_new_num` 就会运行一次,它会立即取消当前正在运行的`run_on_new_num` ,
|
|
|
|
|
// 并且使用新返回的值来替换
|
|
|
|
|
async fn run_loop(
|
|
|
|
|
mut interval_timer: impl Stream<Item = ()> + FusedStream + Unpin,
|
|
|
|
|
starting_num: u8,
|
|
|
|
|
) {
|
|
|
|
|
let mut run_on_new_num_futs = FuturesUnordered::new();
|
|
|
|
|
run_on_new_num_futs.push(run_on_new_num(starting_num));
|
|
|
|
|
let get_new_num_fut = Fuse::terminated();
|
|
|
|
|
pin_mut!(get_new_num_fut);
|
|
|
|
|
loop {
|
|
|
|
|
select! {
|
|
|
|
|
() = interval_timer.select_next_some() => {
|
|
|
|
|
// 定时器已结束,若 `get_new_num_fut` 没有在运行,就创建一个新的
|
|
|
|
|
if get_new_num_fut.is_terminated() {
|
|
|
|
|
get_new_num_fut.set(get_new_num().fuse());
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
new_num = get_new_num_fut => {
|
|
|
|
|
// 收到新的数字 -- 创建一个新的 `run_on_new_num_fut` (并没有像之前的例子那样丢弃掉旧值)
|
|
|
|
|
run_on_new_num_futs.push(run_on_new_num(new_num));
|
|
|
|
|
},
|
|
|
|
|
// 运行 `run_on_new_num_futs`, 并检查是否有已经完成的
|
|
|
|
|
res = run_on_new_num_futs.select_next_some() => {
|
|
|
|
|
println!("run_on_new_num_fut returned {:?}", res);
|
|
|
|
|
},
|
|
|
|
|
// 若所有任务都完成,直接 `panic`, 原因是 `interval_timer` 应该连续不断的产生值,而不是结束
|
|
|
|
|
//后,执行到 `complete` 分支
|
|
|
|
|
complete => panic!("`interval_timer` completed unexpectedly"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<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/async-await.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/pain-points-and-workarounds.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/async-await.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/pain-points-and-workarounds.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/multi-futures-simultaneous.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|