mirror of https://github.com/sunface/rust-course
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
642 lines
73 KiB
642 lines
73 KiB
1 month ago
|
<!DOCTYPE HTML>
|
||
|
<html lang="zh-CN" class="light" dir="ltr">
|
||
|
<head>
|
||
|
<!-- Book generated using mdBook -->
|
||
|
<meta charset="UTF-8">
|
||
|
<title>优雅关闭和资源清理 - 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></li></ol></li><li class="chapter-item "><a href="../basic/flow-control.html"><strong a
|
||
|
</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-practice1/graceful-shutdown.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="优雅关闭和资源清理"><a class="header" href="#优雅关闭和资源清理">优雅关闭和资源清理</a></h1>
|
||
|
<p>之前的程序,如果使用 <code>ctrl-c</code> 的方法来关闭,所有的线程都会立即停止,这会造成正在请求的用户感知到一个明显的错误。</p>
|
||
|
<p>因此我们需要添加一些优雅关闭( Graceful Shutdown ),以更好的完成资源清理等收尾工作。</p>
|
||
|
<h2 id="为线程池实现-drop"><a class="header" href="#为线程池实现-drop">为线程池实现 Drop</a></h2>
|
||
|
<p>当线程池被 drop 时,需要等待所有的子线程完成它们的工作,然后再退出,下面是一个初步尝试:</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>impl Drop for ThreadPool {
|
||
|
fn drop(&mut self) {
|
||
|
for worker in &mut self.workers {
|
||
|
println!("Shutting down worker {}", worker.id);
|
||
|
|
||
|
worker.thread.join().unwrap();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>这里通过实现 <code>Drop</code> 特征来为线程池添加资源收尾工作,代码比较简单,就是依次调用每个线程的 <code>join</code> 方法。编译下试试:</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>$ cargo check
|
||
|
Checking hello v0.1.0 (file:///projects/hello)
|
||
|
error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference
|
||
|
--> src/lib.rs:52:13
|
||
|
|
|
||
|
52 | worker.thread.join().unwrap();
|
||
|
| ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call
|
||
|
| |
|
||
|
| move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait
|
||
|
|
|
||
|
note: this function takes ownership of the receiver `self`, which moves `worker.thread`
|
||
|
|
||
|
For more information about this error, try `rustc --explain E0507`.
|
||
|
error: could not compile `hello` due to previous error
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>这里的报错很明显,<code>worker.thread</code> 试图拿走所有权,但是 <code>worker</code> 仅仅是一个可变借用,显然是不可行的。</p>
|
||
|
<p>目前来看,只能将 <code>thread</code> 从 <code>worker</code> 中移动出来,一个可行的尝试:</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>struct Worker {
|
||
|
id: usize,
|
||
|
thread: Option<thread::JoinHandle<()>>,
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>对于 <code>Option</code> 类型,可以使用 <code>take</code> 方法拿走内部值的所有权,同时留下一个 <code>None</code> 在风中孤独凌乱。继续尝试编译驱动开发模式:</p>
|
||
|
<pre><code class="language-shell">$ cargo check
|
||
|
Checking hello v0.1.0 (file:///projects/hello)
|
||
|
error[E0599]: no method named `join` found for enum `Option` in the current scope
|
||
|
--> src/lib.rs:52:27
|
||
|
|
|
||
|
52 | worker.thread.join().unwrap();
|
||
|
| ^^^^ method not found in `Option<JoinHandle<()>>`
|
||
|
|
|
||
|
note: the method `join` exists on the type `JoinHandle<()>`
|
||
|
help: consider using `Option::expect` to unwrap the `JoinHandle<()>` value, panicking if the value is an `Option::None`
|
||
|
|
|
||
|
52 | worker.thread.expect("REASON").join().unwrap();
|
||
|
| +++++++++++++++++
|
||
|
|
||
|
error[E0308]: mismatched types
|
||
|
--> src/lib.rs:72:22
|
||
|
|
|
||
|
72 | Worker { id, thread }
|
||
|
| ^^^^^^ expected enum `Option`, found struct `JoinHandle`
|
||
|
|
|
||
|
= note: expected enum `Option<JoinHandle<()>>`
|
||
|
found struct `JoinHandle<_>`
|
||
|
help: try wrapping the expression in `Some`
|
||
|
|
|
||
|
72 | Worker { id, thread: Some(thread) }
|
||
|
| +++++++++++++ +
|
||
|
</code></pre>
|
||
|
<p>先来解决第二个类型不匹配的错误:</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>impl Worker {
|
||
|
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
||
|
// --snip--
|
||
|
|
||
|
Worker {
|
||
|
id,
|
||
|
thread: Some(thread),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>简单搞定,回头看看第一个错误,既然换了 <code>Option</code>,就可以用 <code>take</code> 拿走所有权:</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>impl Drop for ThreadPool {
|
||
|
fn drop(&mut self) {
|
||
|
for worker in &mut self.workers {
|
||
|
println!("Shutting down worker {}", worker.id);
|
||
|
|
||
|
if let Some(thread) = worker.thread.take() {
|
||
|
thread.join().unwrap();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>注意这种 <code>if let</code> 的写法,若 <code>worker.thread</code> 已经是 <code>None</code>,什么都不会发生,符合我们的预期; 若包含一个线程,那就拿走其所有权,然后调用 <code>join</code>。</p>
|
||
|
<h2 id="停止工作线程"><a class="header" href="#停止工作线程">停止工作线程</a></h2>
|
||
|
<p>虽然调用了 <code>join</code> ,但是目标线程依然不会停止,原因在于它们在无限的 <code>loop</code> 循环等待,看起来需要借用 <code>channel</code> 的 <code>drop</code> 机制:释放 <code>sender</code>发送端后,<code>receiver</code> 接收端会收到报错,然后再退出即可。</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>pub struct ThreadPool {
|
||
|
workers: Vec<Worker>,
|
||
|
sender: Option<mpsc::Sender<Job>>,
|
||
|
}
|
||
|
// --snip--
|
||
|
impl ThreadPool {
|
||
|
pub fn new(size: usize) -> ThreadPool {
|
||
|
// --snip--
|
||
|
|
||
|
ThreadPool {
|
||
|
workers,
|
||
|
sender: Some(sender),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn execute<F>(&self, f: F)
|
||
|
where
|
||
|
F: FnOnce() + Send + 'static,
|
||
|
{
|
||
|
let job = Box::new(f);
|
||
|
|
||
|
self.sender.as_ref().unwrap().send(job).unwrap();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Drop for ThreadPool {
|
||
|
fn drop(&mut self) {
|
||
|
drop(self.sender.take());
|
||
|
|
||
|
for worker in &mut self.workers {
|
||
|
println!("Shutting down worker {}", worker.id);
|
||
|
|
||
|
if let Some(thread) = worker.thread.take() {
|
||
|
thread.join().unwrap();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>上面做了两处改变:</p>
|
||
|
<ol>
|
||
|
<li>为 <code>sender</code> 增加 <code>Option</code> 封装,这样可以用 <code>take</code> 拿走所有权,跟之前的 <code>thread</code> 一样</li>
|
||
|
<li>主动调用 <code>drop</code> 关闭发送端 <code>sender</code></li>
|
||
|
</ol>
|
||
|
<p>关闭 <code>sender</code> 后,将关闭对应的 <code>channel</code>,意味着不会再有任何消息被发送。随后,所有的处于无限 <code>loop</code> 的接收端将收到一个错误,我们根据错误再进行进一步的处理。</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>impl Worker {
|
||
|
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
||
|
let thread = thread::spawn(move || loop {
|
||
|
let message = receiver.lock().unwrap().recv();
|
||
|
|
||
|
match message {
|
||
|
Ok(job) => {
|
||
|
println!("Worker {id} got a job; executing.");
|
||
|
|
||
|
job();
|
||
|
}
|
||
|
Err(_) => {
|
||
|
println!("Worker {id} disconnected; shutting down.");
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Worker {
|
||
|
id,
|
||
|
thread: Some(thread),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>为了快速验证代码是否正确,修改 <code>main</code> 函数,让其只接收前两个请求:</p>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
||
|
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
||
|
let pool = ThreadPool::new(4);
|
||
|
|
||
|
for stream in listener.incoming().take(2) {
|
||
|
let stream = stream.unwrap();
|
||
|
|
||
|
pool.execute(|| {
|
||
|
handle_connection(stream);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
println!("Shutting down.");
|
||
|
}</code></pre></pre>
|
||
|
<p><code>take</code> 是迭代器 <code>Iterator</code> 上的方法,会限制后续的迭代进行最多两次,然后就结束监听,随后 <code>ThreadPool</code> 也将超出作用域并自动触发 <code>drop</code>。</p>
|
||
|
<pre><code class="language-shell">$ cargo run
|
||
|
Compiling hello v0.1.0 (file:///projects/hello)
|
||
|
Finished dev [unoptimized + debuginfo] target(s) in 1.0s
|
||
|
Running `target/debug/hello`
|
||
|
Worker 0 got a job; executing.
|
||
|
Shutting down.
|
||
|
Shutting down worker 0
|
||
|
Worker 3 got a job; executing.
|
||
|
Worker 1 disconnected; shutting down.
|
||
|
Worker 2 disconnected; shutting down.
|
||
|
Worker 3 disconnected; shutting down.
|
||
|
Worker 0 disconnected; shutting down.
|
||
|
Shutting down worker 1
|
||
|
Shutting down worker 2
|
||
|
Shutting down worker 3
|
||
|
</code></pre>
|
||
|
<p>可以看到,代码按照我们的设想如期运行,至此,一个基于线程池的简单 Web 服务器已经完成,下面是完整的代码:</p>
|
||
|
<h2 id="完整代码"><a class="header" href="#完整代码">完整代码</a></h2>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021">// src/main.rs
|
||
|
use hello::ThreadPool;
|
||
|
use std::fs;
|
||
|
use std::io::prelude::*;
|
||
|
use std::net::TcpListener;
|
||
|
use std::net::TcpStream;
|
||
|
use std::thread;
|
||
|
use std::time::Duration;
|
||
|
|
||
|
fn main() {
|
||
|
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
||
|
let pool = ThreadPool::new(4);
|
||
|
|
||
|
for stream in listener.incoming().take(2) {
|
||
|
let stream = stream.unwrap();
|
||
|
|
||
|
pool.execute(|| {
|
||
|
handle_connection(stream);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
println!("Shutting down.");
|
||
|
}
|
||
|
|
||
|
fn handle_connection(mut stream: TcpStream) {
|
||
|
let mut buffer = [0; 1024];
|
||
|
stream.read(&mut buffer).unwrap();
|
||
|
|
||
|
let get = b"GET / HTTP/1.1\r\n";
|
||
|
let sleep = b"GET /sleep HTTP/1.1\r\n";
|
||
|
|
||
|
let (status_line, filename) = if buffer.starts_with(get) {
|
||
|
("HTTP/1.1 200 OK", "hello.html")
|
||
|
} else if buffer.starts_with(sleep) {
|
||
|
thread::sleep(Duration::from_secs(5));
|
||
|
("HTTP/1.1 200 OK", "hello.html")
|
||
|
} else {
|
||
|
("HTTP/1.1 404 NOT FOUND", "404.html")
|
||
|
};
|
||
|
|
||
|
let contents = fs::read_to_string(filename).unwrap();
|
||
|
|
||
|
let response = format!(
|
||
|
"{}\r\nContent-Length: {}\r\n\r\n{}",
|
||
|
status_line,
|
||
|
contents.len(),
|
||
|
contents
|
||
|
);
|
||
|
|
||
|
stream.write_all(response.as_bytes()).unwrap();
|
||
|
stream.flush().unwrap();
|
||
|
}</code></pre></pre>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>// src/lib.rs
|
||
|
use std::{
|
||
|
sync::{mpsc, Arc, Mutex},
|
||
|
thread,
|
||
|
};
|
||
|
|
||
|
pub struct ThreadPool {
|
||
|
workers: Vec<Worker>,
|
||
|
sender: Option<mpsc::Sender<Job>>,
|
||
|
}
|
||
|
|
||
|
type Job = Box<dyn FnOnce() + Send + 'static>;
|
||
|
|
||
|
impl ThreadPool {
|
||
|
/// Create a new ThreadPool.
|
||
|
///
|
||
|
/// The size is the number of threads in the pool.
|
||
|
///
|
||
|
/// # Panics
|
||
|
///
|
||
|
/// The `new` function will panic if the size is zero.
|
||
|
pub fn new(size: usize) -> ThreadPool {
|
||
|
assert!(size > 0);
|
||
|
|
||
|
let (sender, receiver) = mpsc::channel();
|
||
|
|
||
|
let receiver = Arc::new(Mutex::new(receiver));
|
||
|
|
||
|
let mut workers = Vec::with_capacity(size);
|
||
|
|
||
|
for id in 0..size {
|
||
|
workers.push(Worker::new(id, Arc::clone(&receiver)));
|
||
|
}
|
||
|
|
||
|
ThreadPool {
|
||
|
workers,
|
||
|
sender: Some(sender),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn execute<F>(&self, f: F)
|
||
|
where
|
||
|
F: FnOnce() + Send + 'static,
|
||
|
{
|
||
|
let job = Box::new(f);
|
||
|
|
||
|
self.sender.as_ref().unwrap().send(job).unwrap();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Drop for ThreadPool {
|
||
|
fn drop(&mut self) {
|
||
|
drop(self.sender.take());
|
||
|
|
||
|
for worker in &mut self.workers {
|
||
|
println!("Shutting down worker {}", worker.id);
|
||
|
|
||
|
if let Some(thread) = worker.thread.take() {
|
||
|
thread.join().unwrap();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
struct Worker {
|
||
|
id: usize,
|
||
|
thread: Option<thread::JoinHandle<()>>,
|
||
|
}
|
||
|
|
||
|
impl Worker {
|
||
|
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
||
|
let thread = thread::spawn(move || loop {
|
||
|
let message = receiver.lock().unwrap().recv();
|
||
|
|
||
|
match message {
|
||
|
Ok(job) => {
|
||
|
println!("Worker {id} got a job; executing.");
|
||
|
|
||
|
job();
|
||
|
}
|
||
|
Err(_) => {
|
||
|
println!("Worker {id} disconnected; shutting down.");
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Worker {
|
||
|
id,
|
||
|
thread: Some(thread),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<h3 id="可以做的更多"><a class="header" href="#可以做的更多">可以做的更多</a></h3>
|
||
|
<p>事实上,我们还可以做更多,但是受制于篇幅,就不再展开,感兴趣的同学可以自行完成。</p>
|
||
|
<ul>
|
||
|
<li>增加更多的文档</li>
|
||
|
<li>为线程池增加测试</li>
|
||
|
<li>尽可能移除 <code>unwrap</code>,替换为错误处理</li>
|
||
|
<li>使用线程池完成其它类型的工作,而不仅仅是本章的 Web 服务器</li>
|
||
|
<li>在 <code>crates.io</code> 上找到一个线程池实现,然后使用该包实现一个类似的 Web 服务器</li>
|
||
|
</ul>
|
||
|
<h2 id="上一章节的遗留问题"><a class="header" href="#上一章节的遗留问题">上一章节的遗留问题</a></h2>
|
||
|
<p>在上一章节的末尾,我们提到将 <code>let</code> 替换为 <code>while let</code> 后,多线程的优势将荡然无存,原因藏的很隐蔽:</p>
|
||
|
<ol>
|
||
|
<li><code>Mutex</code> 结构体没有提供显式的 <code>unlock</code>,要依赖作用域结束后的 <code>drop</code> 来自动释放 </li>
|
||
|
<li><code>let job = receiver.lock().unwrap().recv().unwrap();</code> 在这行代码中,由于使用了 <code>let</code>,右边的任何临时变量会在 <code>let</code> 语句结束后立即被 <code>drop</code>,因此锁会自动释放</li>
|
||
|
<li>然而 <code>while let</code> (还包括 <code>if let</code> 和 <code>match</code>) 直到最后一个花括号后,才触发 <code>drop</code></li>
|
||
|
</ol>
|
||
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
||
|
</span><span class="boring">fn main() {
|
||
|
</span>impl Worker {
|
||
|
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
||
|
let thread = thread::spawn(move || {
|
||
|
while let Ok(job) = receiver.lock().unwrap().recv() {
|
||
|
println!("Worker {id} got a job; executing.");
|
||
|
|
||
|
job();
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Worker { id, thread }
|
||
|
}
|
||
|
}
|
||
|
<span class="boring">}</span></code></pre></pre>
|
||
|
<p>根据之前的分析,上面的代码直到 <code>job()</code> 任务执行结束后,才会释放锁,去执行另一个请求,最终造成请求排队。</p>
|
||
|
|
||
|
<div id="giscus-container"></div>
|
||
|
</main>
|
||
|
|
||
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
||
|
<!-- Mobile navigation buttons -->
|
||
|
<a rel="prev" href="../advance-practice1/multi-threads.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-practice/intro.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-practice1/multi-threads.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-practice/intro.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-practice1/graceful-shutdown.md"
|
||
|
</script>
|
||
|
|
||
|
|
||
|
<!-- Custom JS scripts -->
|
||
|
<script src="../assets/custom.js"></script>
|
||
|
<script src="../assets/bigPicture.js"></script>
|
||
|
|
||
|
|
||
|
</div>
|
||
|
</body>
|
||
|
</html>
|