build: 2026-06-22
This commit is contained in:
773
build/ch17-02-concurrency-with-async.html
Normal file
773
build/ch17-02-concurrency-with-async.html
Normal file
@@ -0,0 +1,773 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en" class="light sidebar-visible" dir="ltr">
|
||||
<head>
|
||||
<!-- Book generated using mdBook -->
|
||||
<meta charset="UTF-8">
|
||||
<title>Applying Concurrency with Async - The Rust Programming Language</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-0392ca55.css">
|
||||
<link rel="stylesheet" href="css/chrome-fc474251.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="ferris-d33b75bf.css">
|
||||
<link rel="stylesheet" href="theme/2018-edition-4e126c62.css">
|
||||
<link rel="stylesheet" href="theme/semantic-notes-9b5766c0.css">
|
||||
<link rel="stylesheet" href="theme/listing-cab26221.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-6a1da8cc.js";
|
||||
</script>
|
||||
<!-- Start loading toc.js asap -->
|
||||
<script src="toc-0e4ce700.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">The Rust Programming Language</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/rust-lang/book" 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>
|
||||
|
||||
</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>
|
||||
<!-- Old headings. Do not remove or links may break. -->
|
||||
<p><a id="concurrency-with-async"></a></p>
|
||||
<h2 id="applying-concurrency-with-async"><a class="header" href="#applying-concurrency-with-async">Applying Concurrency with Async</a></h2>
|
||||
<p>In this section, we’ll apply async to some of the same concurrency challenges
|
||||
we tackled with threads in Chapter 16. Because we already talked about a lot of
|
||||
the key ideas there, in this section we’ll focus on what’s different between
|
||||
threads and futures.</p>
|
||||
<p>In many cases, the APIs for working with concurrency using async are very
|
||||
similar to those for using threads. In other cases, they end up being quite
|
||||
different. Even when the APIs <em>look</em> similar between threads and async, they
|
||||
often have different behavior—and they nearly always have different performance
|
||||
characteristics.</p>
|
||||
<!-- Old headings. Do not remove or links may break. -->
|
||||
<p><a id="counting"></a></p>
|
||||
<h3 id="creating-a-new-task-with-spawn_task"><a class="header" href="#creating-a-new-task-with-spawn_task">Creating a New Task with <code>spawn_task</code></a></h3>
|
||||
<p>The first operation we tackled in the <a href="ch16-01-threads.html#creating-a-new-thread-with-spawn">“Creating a New Thread with
|
||||
<code>spawn</code>”</a><!-- ignore --> section in Chapter 16 was counting up on
|
||||
two separate threads. Let’s do the same using async. The <code>trpl</code> crate supplies
|
||||
a <code>spawn_task</code> function that looks very similar to the <code>thread::spawn</code> API, and
|
||||
a <code>sleep</code> function that is an async version of the <code>thread::sleep</code> API. We can
|
||||
use these together to implement the counting example, as shown in Listing 17-6.</p>
|
||||
<figure class="listing" id="listing-17-6">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span>use std::time::Duration;
|
||||
|
||||
fn main() {
|
||||
trpl::block_on(async {
|
||||
trpl::spawn_task(async {
|
||||
for i in 1..10 {
|
||||
println!("hi number {i} from the first task!");
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
});
|
||||
|
||||
for i in 1..5 {
|
||||
println!("hi number {i} from the second task!");
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
});
|
||||
}</code></pre>
|
||||
<figcaption><a href="#listing-17-6">Listing 17-6</a>: Creating a new task to print one thing while the main task prints something else</figcaption>
|
||||
</figure>
|
||||
<p>As our starting point, we set up our <code>main</code> function with <code>trpl::block_on</code> so
|
||||
that our top-level function can be async.</p>
|
||||
<section class="note" aria-role="note">
|
||||
<p>Note: From this point forward in the chapter, every example will include this
|
||||
exact same wrapping code with <code>trpl::block_on</code> in <code>main</code>, so we’ll often skip it
|
||||
just as we do with <code>main</code>. Remember to include it in your code!</p>
|
||||
</section>
|
||||
<p>Then we write two loops within that block, each containing a <code>trpl::sleep</code>
|
||||
call, which waits for half a second (500 milliseconds) before sending the next
|
||||
message. We put one loop in the body of a <code>trpl::spawn_task</code> and the other in a
|
||||
top-level <code>for</code> loop. We also add an <code>await</code> after the <code>sleep</code> calls.</p>
|
||||
<p>This code behaves similarly to the thread-based implementation—including the
|
||||
fact that you may see the messages appear in a different order in your own
|
||||
terminal when you run it:</p>
|
||||
<!-- Not extracting output because changes to this output aren't significant;
|
||||
the changes are likely to be due to the threads running differently rather than
|
||||
changes in the compiler -->
|
||||
<pre><code class="language-text">hi number 1 from the second task!
|
||||
hi number 1 from the first task!
|
||||
hi number 2 from the first task!
|
||||
hi number 2 from the second task!
|
||||
hi number 3 from the first task!
|
||||
hi number 3 from the second task!
|
||||
hi number 4 from the first task!
|
||||
hi number 4 from the second task!
|
||||
hi number 5 from the first task!
|
||||
</code></pre>
|
||||
<p>This version stops as soon as the <code>for</code> loop in the body of the main async
|
||||
block finishes, because the task spawned by <code>spawn_task</code> is shut down when the
|
||||
<code>main</code> function ends. If you want it to run all the way to the task’s
|
||||
completion, you will need to use a join handle to wait for the first task to
|
||||
complete. With threads, we used the <code>join</code> method to “block” until the thread
|
||||
was done running. In Listing 17-7, we can use <code>await</code> to do the same thing,
|
||||
because the task handle itself is a future. Its <code>Output</code> type is a <code>Result</code>, so
|
||||
we also unwrap it after awaiting it.</p>
|
||||
<figure class="listing" id="listing-17-7">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">use std::time::Duration;
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span> let handle = trpl::spawn_task(async {
|
||||
for i in 1..10 {
|
||||
println!("hi number {i} from the first task!");
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
});
|
||||
|
||||
for i in 1..5 {
|
||||
println!("hi number {i} from the second task!");
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
<span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-7">Listing 17-7</a>: Using <code>await</code> with a join handle to run a task to completion</figcaption>
|
||||
</figure>
|
||||
<p>This updated version runs until <em>both</em> loops finish:</p>
|
||||
<!-- Not extracting output because changes to this output aren't significant;
|
||||
the changes are likely to be due to the threads running differently rather than
|
||||
changes in the compiler -->
|
||||
<pre><code class="language-text">hi number 1 from the second task!
|
||||
hi number 1 from the first task!
|
||||
hi number 2 from the first task!
|
||||
hi number 2 from the second task!
|
||||
hi number 3 from the first task!
|
||||
hi number 3 from the second task!
|
||||
hi number 4 from the first task!
|
||||
hi number 4 from the second task!
|
||||
hi number 5 from the first task!
|
||||
hi number 6 from the first task!
|
||||
hi number 7 from the first task!
|
||||
hi number 8 from the first task!
|
||||
hi number 9 from the first task!
|
||||
</code></pre>
|
||||
<p>So far, it looks like async and threads give us similar outcomes, just with
|
||||
different syntax: using <code>await</code> instead of calling <code>join</code> on the join handle,
|
||||
and awaiting the <code>sleep</code> calls.</p>
|
||||
<p>The bigger difference is that we didn’t need to spawn another operating system
|
||||
thread to do this. In fact, we don’t even need to spawn a task here. Because
|
||||
async blocks compile to anonymous futures, we can put each loop in an async
|
||||
block and have the runtime run them both to completion using the <code>trpl::join</code>
|
||||
function.</p>
|
||||
<p>In the <a href="ch16-01-threads.html#waiting-for-all-threads-to-finish">“Waiting for All Threads to Finish”</a><!-- ignore -->
|
||||
section in Chapter 16, we showed how to use the <code>join</code> method on the
|
||||
<code>JoinHandle</code> type returned when you call <code>std::thread::spawn</code>. The <code>trpl::join</code>
|
||||
function is similar, but for futures. When you give it two futures, it produces
|
||||
a single new future whose output is a tuple containing the output of each
|
||||
future you passed in once they <em>both</em> complete. Thus, in Listing 17-8, we use
|
||||
<code>trpl::join</code> to wait for both <code>fut1</code> and <code>fut2</code> to finish. We do <em>not</em> await
|
||||
<code>fut1</code> and <code>fut2</code> but instead the new future produced by <code>trpl::join</code>. We
|
||||
ignore the output, because it’s just a tuple containing two unit values.</p>
|
||||
<figure class="listing" id="listing-17-8">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">use std::time::Duration;
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span> let fut1 = async {
|
||||
for i in 1..10 {
|
||||
println!("hi number {i} from the first task!");
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
};
|
||||
|
||||
let fut2 = async {
|
||||
for i in 1..5 {
|
||||
println!("hi number {i} from the second task!");
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
};
|
||||
|
||||
trpl::join(fut1, fut2).await;
|
||||
<span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-8">Listing 17-8</a>: Using <code>trpl::join</code> to await two anonymous futures</figcaption>
|
||||
</figure>
|
||||
<p>When we run this, we see both futures run to completion:</p>
|
||||
<!-- Not extracting output because changes to this output aren't significant;
|
||||
the changes are likely to be due to the threads running differently rather than
|
||||
changes in the compiler -->
|
||||
<pre><code class="language-text">hi number 1 from the first task!
|
||||
hi number 1 from the second task!
|
||||
hi number 2 from the first task!
|
||||
hi number 2 from the second task!
|
||||
hi number 3 from the first task!
|
||||
hi number 3 from the second task!
|
||||
hi number 4 from the first task!
|
||||
hi number 4 from the second task!
|
||||
hi number 5 from the first task!
|
||||
hi number 6 from the first task!
|
||||
hi number 7 from the first task!
|
||||
hi number 8 from the first task!
|
||||
hi number 9 from the first task!
|
||||
</code></pre>
|
||||
<p>Now, you’ll see the exact same order every time, which is very different from
|
||||
what we saw with threads and with <code>trpl::spawn_task</code> in Listing 17-7. That is
|
||||
because the <code>trpl::join</code> function is <em>fair</em>, meaning it checks each future
|
||||
equally often, alternating between them, and never lets one race ahead if the
|
||||
other is ready. With threads, the operating system decides which thread to
|
||||
check and how long to let it run. With async Rust, the runtime decides which
|
||||
task to check. (In practice, the details get complicated because an async
|
||||
runtime might use operating system threads under the hood as part of how it
|
||||
manages concurrency, so guaranteeing fairness can be more work for a
|
||||
runtime—but it’s still possible!) Runtimes don’t have to guarantee fairness for
|
||||
any given operation, and they often offer different APIs to let you choose
|
||||
whether or not you want fairness.</p>
|
||||
<p>Try some of these variations on awaiting the futures and see what they do:</p>
|
||||
<ul>
|
||||
<li>Remove the async block from around either or both of the loops.</li>
|
||||
<li>Await each async block immediately after defining it.</li>
|
||||
<li>Wrap only the first loop in an async block, and await the resulting future
|
||||
after the body of second loop.</li>
|
||||
</ul>
|
||||
<p>For an extra challenge, see if you can figure out what the output will be in
|
||||
each case <em>before</em> running the code!</p>
|
||||
<!-- Old headings. Do not remove or links may break. -->
|
||||
<p><a id="message-passing"></a>
|
||||
<a id="counting-up-on-two-tasks-using-message-passing"></a></p>
|
||||
<h3 id="sending-data-between-two-tasks-using-message-passing"><a class="header" href="#sending-data-between-two-tasks-using-message-passing">Sending Data Between Two Tasks Using Message Passing</a></h3>
|
||||
<p>Sharing data between futures will also be familiar: we’ll use message passing
|
||||
again, but this time with async versions of the types and functions. We’ll take
|
||||
a slightly different path than we did in the <a href="ch16-02-message-passing.html">“Transfer Data Between Threads
|
||||
with Message Passing”</a><!-- ignore --> section in
|
||||
Chapter 16 to illustrate some of the key differences between thread-based and
|
||||
futures-based concurrency. In Listing 17-9, we’ll begin with just a single
|
||||
async block—<em>not</em> spawning a separate task as we spawned a separate thread.</p>
|
||||
<figure class="listing" id="listing-17-9">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span> let (tx, mut rx) = trpl::channel();
|
||||
|
||||
let val = String::from("hi");
|
||||
tx.send(val).unwrap();
|
||||
|
||||
let received = rx.recv().await.unwrap();
|
||||
println!("received '{received}'");
|
||||
<span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-9">Listing 17-9</a>: Creating an async channel and assigning the two halves to <code>tx</code> and <code>rx</code></figcaption>
|
||||
</figure>
|
||||
<p>Here, we use <code>trpl::channel</code>, an async version of the multiple-producer,
|
||||
single-consumer channel API we used with threads back in Chapter 16. The async
|
||||
version of the API is only a little different from the thread-based version: it
|
||||
uses a mutable rather than an immutable receiver <code>rx</code>, and its <code>recv</code> method
|
||||
produces a future we need to await rather than producing the value directly.
|
||||
Now we can send messages from the sender to the receiver. Notice that we don’t
|
||||
have to spawn a separate thread or even a task; we merely need to await the
|
||||
<code>rx.recv</code> call.</p>
|
||||
<p>The synchronous <code>Receiver::recv</code> method in <code>std::mpsc::channel</code> blocks until it
|
||||
receives a message. The <code>trpl::Receiver::recv</code> method does not, because it is
|
||||
async. Instead of blocking, it hands control back to the runtime until either a
|
||||
message is received or the send side of the channel closes. By contrast, we
|
||||
don’t await the <code>send</code> call, because it doesn’t block. It doesn’t need to,
|
||||
because the channel we’re sending it into is unbounded.</p>
|
||||
<section class="note" aria-role="note">
|
||||
<p>Note: Because all of this async code runs in an async block in a
|
||||
<code>trpl::block_on</code> call, everything within it can avoid blocking. However, the
|
||||
code <em>outside</em> it will block on the <code>block_on</code> function returning. That’s the
|
||||
whole point of the <code>trpl::block_on</code> function: it lets you <em>choose</em> where to
|
||||
block on some set of async code, and thus where to transition between sync
|
||||
and async code.</p>
|
||||
</section>
|
||||
<p>Notice two things about this example. First, the message will arrive right
|
||||
away. Second, although we use a future here, there’s no concurrency yet.
|
||||
Everything in the listing happens in sequence, just as it would if there were
|
||||
no futures involved.</p>
|
||||
<p>Let’s address the first part by sending a series of messages and sleeping in
|
||||
between them, as shown in Listing 17-10.</p>
|
||||
<!-- We cannot test this one because it never stops! -->
|
||||
<figure class="listing" id="listing-17-10">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust ignore"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">use std::time::Duration;
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span> let (tx, mut rx) = trpl::channel();
|
||||
|
||||
let vals = vec![
|
||||
String::from("hi"),
|
||||
String::from("from"),
|
||||
String::from("the"),
|
||||
String::from("future"),
|
||||
];
|
||||
|
||||
for val in vals {
|
||||
tx.send(val).unwrap();
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
while let Some(value) = rx.recv().await {
|
||||
println!("received '{value}'");
|
||||
}
|
||||
<span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-10">Listing 17-10</a>: Sending and receiving multiple messages over the async channel and sleeping with an <code>await</code> between each message</figcaption>
|
||||
</figure>
|
||||
<p>In addition to sending the messages, we need to receive them. In this case,
|
||||
because we know how many messages are coming in, we could do that manually by
|
||||
calling <code>rx.recv().await</code> four times. In the real world, though, we’ll generally
|
||||
be waiting on some <em>unknown</em> number of messages, so we need to keep waiting
|
||||
until we determine that there are no more messages.</p>
|
||||
<p>In Listing 16-10, we used a <code>for</code> loop to process all the items received from a
|
||||
synchronous channel. Rust doesn’t yet have a way to use a <code>for</code> loop with an
|
||||
<em>asynchronously produced</em> series of items, however, so we need to use a loop we
|
||||
haven’t seen before: the <code>while let</code> conditional loop. This is the loop version
|
||||
of the <code>if let</code> construct we saw back in the <a href="ch06-03-if-let.html">“Concise Control Flow with <code>if let</code> and <code>let...else</code>”</a><!-- ignore --> section in Chapter 6. The loop
|
||||
will continue executing as long as the pattern it specifies continues to match
|
||||
the value.</p>
|
||||
<p>The <code>rx.recv</code> call produces a future, which we await. The runtime will pause
|
||||
the future until it is ready. Once a message arrives, the future will resolve
|
||||
to <code>Some(message)</code> as many times as a message arrives. When the channel closes,
|
||||
regardless of whether <em>any</em> messages have arrived, the future will instead
|
||||
resolve to <code>None</code> to indicate that there are no more values and thus we should
|
||||
stop polling—that is, stop awaiting.</p>
|
||||
<p>The <code>while let</code> loop pulls all of this together. If the result of calling
|
||||
<code>rx.recv().await</code> is <code>Some(message)</code>, we get access to the message and we can
|
||||
use it in the loop body, just as we could with <code>if let</code>. If the result is
|
||||
<code>None</code>, the loop ends. Every time the loop completes, it hits the await point
|
||||
again, so the runtime pauses it again until another message arrives.</p>
|
||||
<p>The code now successfully sends and receives all of the messages.
|
||||
Unfortunately, there are still a couple of problems. For one thing, the
|
||||
messages do not arrive at half-second intervals. They arrive all at once, 2
|
||||
seconds (2,000 milliseconds) after we start the program. For another, this
|
||||
program also never exits! Instead, it waits forever for new messages. You will
|
||||
need to shut it down using <kbd>ctrl</kbd>-<kbd>C</kbd>.</p>
|
||||
<h4 id="code-within-one-async-block-executes-linearly"><a class="header" href="#code-within-one-async-block-executes-linearly">Code Within One Async Block Executes Linearly</a></h4>
|
||||
<p>Let’s start by examining why the messages come in all at once after the full
|
||||
delay, rather than coming in with delays between each one. Within a given async
|
||||
block, the order in which <code>await</code> keywords appear in the code is also the order
|
||||
in which they’re executed when the program runs.</p>
|
||||
<p>There’s only one async block in Listing 17-10, so everything in it runs
|
||||
linearly. There’s still no concurrency. All the <code>tx.send</code> calls happen,
|
||||
interspersed with all of the <code>trpl::sleep</code> calls and their associated await
|
||||
points. Only then does the <code>while let</code> loop get to go through any of the
|
||||
<code>await</code> points on the <code>recv</code> calls.</p>
|
||||
<p>To get the behavior we want, where the sleep delay happens between each
|
||||
message, we need to put the <code>tx</code> and <code>rx</code> operations in their own async blocks,
|
||||
as shown in Listing 17-11. Then the runtime can execute each of them separately
|
||||
using <code>trpl::join</code>, just as in Listing 17-8. Once again, we await the result of
|
||||
calling <code>trpl::join</code>, not the individual futures. If we awaited the individual
|
||||
futures in sequence, we would just end up back in a sequential flow—exactly
|
||||
what we’re trying <em>not</em> to do.</p>
|
||||
<!-- We cannot test this one because it never stops! -->
|
||||
<figure class="listing" id="listing-17-11">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust ignore"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">use std::time::Duration;
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span><span class="boring"> let (tx, mut rx) = trpl::channel();
|
||||
</span><span class="boring">
|
||||
</span> let tx_fut = async {
|
||||
let vals = vec![
|
||||
String::from("hi"),
|
||||
String::from("from"),
|
||||
String::from("the"),
|
||||
String::from("future"),
|
||||
];
|
||||
|
||||
for val in vals {
|
||||
tx.send(val).unwrap();
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
};
|
||||
|
||||
let rx_fut = async {
|
||||
while let Some(value) = rx.recv().await {
|
||||
println!("received '{value}'");
|
||||
}
|
||||
};
|
||||
|
||||
trpl::join(tx_fut, rx_fut).await;
|
||||
<span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-11">Listing 17-11</a>: Separating <code>send</code> and <code>recv</code> into their own <code>async</code> blocks and awaiting the futures for those blocks</figcaption>
|
||||
</figure>
|
||||
<p>With the updated code in Listing 17-11, the messages get printed at
|
||||
500-millisecond intervals, rather than all in a rush after 2 seconds.</p>
|
||||
<h4 id="moving-ownership-into-an-async-block"><a class="header" href="#moving-ownership-into-an-async-block">Moving Ownership Into an Async Block</a></h4>
|
||||
<p>The program still never exits, though, because of the way the <code>while let</code> loop
|
||||
interacts with <code>trpl::join</code>:</p>
|
||||
<ul>
|
||||
<li>The future returned from <code>trpl::join</code> completes only once <em>both</em> futures
|
||||
passed to it have completed.</li>
|
||||
<li>The <code>tx_fut</code> future completes once it finishes sleeping after sending the last
|
||||
message in <code>vals</code>.</li>
|
||||
<li>The <code>rx_fut</code> future won’t complete until the <code>while let</code> loop ends.</li>
|
||||
<li>The <code>while let</code> loop won’t end until awaiting <code>rx.recv</code> produces <code>None</code>.</li>
|
||||
<li>Awaiting <code>rx.recv</code> will return <code>None</code> only once the other end of the channel
|
||||
is closed.</li>
|
||||
<li>The channel will close only if we call <code>rx.close</code> or when the sender side,
|
||||
<code>tx</code>, is dropped.</li>
|
||||
<li>We don’t call <code>rx.close</code> anywhere, and <code>tx</code> won’t be dropped until the
|
||||
outermost async block passed to <code>trpl::block_on</code> ends.</li>
|
||||
<li>The block can’t end because it is blocked on <code>trpl::join</code> completing, which
|
||||
takes us back to the top of this list.</li>
|
||||
</ul>
|
||||
<p>Right now, the async block where we send the messages only <em>borrows</em> <code>tx</code>
|
||||
because sending a message doesn’t require ownership, but if we could <em>move</em>
|
||||
<code>tx</code> into that async block, it would be dropped once that block ends. In the
|
||||
<a href="ch13-01-closures.html#capturing-references-or-moving-ownership">“Capturing References or Moving Ownership”</a><!-- ignore -->
|
||||
section in Chapter 13, you learned how to use the <code>move</code> keyword with closures,
|
||||
and, as discussed in the <a href="ch16-01-threads.html#using-move-closures-with-threads">“Using <code>move</code> Closures with
|
||||
Threads”</a><!-- ignore --> section in Chapter 16, we often need to
|
||||
move data into closures when working with threads. The same basic dynamics
|
||||
apply to async blocks, so the <code>move</code> keyword works with async blocks just as it
|
||||
does with closures.</p>
|
||||
<p>In Listing 17-12, we change the block used to send messages from <code>async</code> to
|
||||
<code>async move</code>.</p>
|
||||
<figure class="listing" id="listing-17-12">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">use std::time::Duration;
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span> let (tx, mut rx) = trpl::channel();
|
||||
|
||||
let tx_fut = async move {
|
||||
// --snip--
|
||||
<span class="boring"> let vals = vec![
|
||||
</span><span class="boring"> String::from("hi"),
|
||||
</span><span class="boring"> String::from("from"),
|
||||
</span><span class="boring"> String::from("the"),
|
||||
</span><span class="boring"> String::from("future"),
|
||||
</span><span class="boring"> ];
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> for val in vals {
|
||||
</span><span class="boring"> tx.send(val).unwrap();
|
||||
</span><span class="boring"> trpl::sleep(Duration::from_millis(500)).await;
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> };
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> let rx_fut = async {
|
||||
</span><span class="boring"> while let Some(value) = rx.recv().await {
|
||||
</span><span class="boring"> println!("received '{value}'");
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> };
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> trpl::join(tx_fut, rx_fut).await;
|
||||
</span><span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-12">Listing 17-12</a>: A revision of the code from Listing 17-11 that correctly shuts down when complete</figcaption>
|
||||
</figure>
|
||||
<p>When we run <em>this</em> version of the code, it shuts down gracefully after the last
|
||||
message is sent and received. Next, let’s see what would need to change to send
|
||||
data from more than one future.</p>
|
||||
<h4 id="joining-a-number-of-futures-with-the-join-macro"><a class="header" href="#joining-a-number-of-futures-with-the-join-macro">Joining a Number of Futures with the <code>join!</code> Macro</a></h4>
|
||||
<p>This async channel is also a multiple-producer channel, so we can call <code>clone</code>
|
||||
on <code>tx</code> if we want to send messages from multiple futures, as shown in Listing
|
||||
17-13.</p>
|
||||
<figure class="listing" id="listing-17-13">
|
||||
<span class="file-name">Filename: src/main.rs</span>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">extern crate trpl; // required for mdbook test
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">use std::time::Duration;
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> trpl::block_on(async {
|
||||
</span> let (tx, mut rx) = trpl::channel();
|
||||
|
||||
let tx1 = tx.clone();
|
||||
let tx1_fut = async move {
|
||||
let vals = vec![
|
||||
String::from("hi"),
|
||||
String::from("from"),
|
||||
String::from("the"),
|
||||
String::from("future"),
|
||||
];
|
||||
|
||||
for val in vals {
|
||||
tx1.send(val).unwrap();
|
||||
trpl::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
};
|
||||
|
||||
let rx_fut = async {
|
||||
while let Some(value) = rx.recv().await {
|
||||
println!("received '{value}'");
|
||||
}
|
||||
};
|
||||
|
||||
let tx_fut = async move {
|
||||
let vals = vec![
|
||||
String::from("more"),
|
||||
String::from("messages"),
|
||||
String::from("for"),
|
||||
String::from("you"),
|
||||
];
|
||||
|
||||
for val in vals {
|
||||
tx.send(val).unwrap();
|
||||
trpl::sleep(Duration::from_millis(1500)).await;
|
||||
}
|
||||
};
|
||||
|
||||
trpl::join!(tx1_fut, tx_fut, rx_fut);
|
||||
<span class="boring"> });
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-17-13">Listing 17-13</a>: Using multiple producers with async blocks</figcaption>
|
||||
</figure>
|
||||
<p>First, we clone <code>tx</code>, creating <code>tx1</code> outside the first async block. We move
|
||||
<code>tx1</code> into that block just as we did before with <code>tx</code>. Then, later, we move the
|
||||
original <code>tx</code> into a <em>new</em> async block, where we send more messages on a
|
||||
slightly slower delay. We happen to put this new async block after the async
|
||||
block for receiving messages, but it could go before it just as well. The key is
|
||||
the order in which the futures are awaited, not in which they’re created.</p>
|
||||
<p>Both of the async blocks for sending messages need to be <code>async move</code> blocks so
|
||||
that both <code>tx</code> and <code>tx1</code> get dropped when those blocks finish. Otherwise, we’ll
|
||||
end up back in the same infinite loop we started out in.</p>
|
||||
<p>Finally, we switch from <code>trpl::join</code> to <code>trpl::join!</code> to handle the additional
|
||||
future: the <code>join!</code> macro awaits an arbitrary number of futures where we know
|
||||
the number of futures at compile time. We’ll discuss awaiting a collection of
|
||||
an unknown number of futures later in this chapter.</p>
|
||||
<p>Now we see all the messages from both sending futures, and because the sending
|
||||
futures use slightly different delays after sending, the messages are also
|
||||
received at those different intervals:</p>
|
||||
<!-- Not extracting output because changes to this output aren't significant;
|
||||
the changes are likely to be due to the threads running differently rather than
|
||||
changes in the compiler -->
|
||||
<pre><code class="language-text">received 'hi'
|
||||
received 'more'
|
||||
received 'from'
|
||||
received 'the'
|
||||
received 'messages'
|
||||
received 'future'
|
||||
received 'for'
|
||||
received 'you'
|
||||
</code></pre>
|
||||
<p>We’ve explored how to use message passing to send data between futures, how
|
||||
code within an async block runs sequentially, how to move ownership into an
|
||||
async block, and how to join multiple futures. Next, let’s discuss how and why
|
||||
to tell the runtime it can switch to another task.</p>
|
||||
|
||||
</main>
|
||||
|
||||
<nav class="nav-wrapper" aria-label="Page navigation">
|
||||
<!-- Mobile navigation buttons -->
|
||||
<a rel="prev" href="ch17-01-futures-and-syntax.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="ch17-03-more-futures.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="ch17-01-futures-and-syntax.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="ch17-03-more-futures.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="elasticlunr-ef4e11c1.min.js"></script>
|
||||
<script src="mark-09e88c2c.min.js"></script>
|
||||
<script src="searcher-09f2665d.js"></script>
|
||||
|
||||
<script src="clipboard-1626706a.min.js"></script>
|
||||
<script src="highlight-abc7f01d.js"></script>
|
||||
<script src="book-c22b7243.js"></script>
|
||||
|
||||
<!-- Custom JS scripts -->
|
||||
<script src="ferris-2317480c.js"></script>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user