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.
503 lines
31 KiB
503 lines
31 KiB
<!DOCTYPE HTML>
|
|
<html lang="zh-CN" class="sidebar-visible no-js light">
|
|
<head>
|
|
<!-- Book generated using mdBook -->
|
|
<meta charset="UTF-8">
|
|
<title>线程 - Rusty Book(锈书)</title>
|
|
<!-- Custom HTML head -->
|
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
|
<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/style1.css">
|
|
</head>
|
|
<body>
|
|
<!-- Provide site root to javascript -->
|
|
<script type="text/javascript">
|
|
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 type="text/javascript">
|
|
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 type="text/javascript">
|
|
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('no-js')
|
|
html.classList.remove('light')
|
|
html.classList.add(theme);
|
|
html.classList.add('js');
|
|
</script>
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
<script type="text/javascript">
|
|
var html = document.querySelector('html');
|
|
var sidebar = 'hidden';
|
|
if (document.body.clientWidth >= 1080) {
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
sidebar = sidebar || 'visible';
|
|
}
|
|
html.classList.remove('sidebar-visible');
|
|
html.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 expanded affix "><a href="../about.html">Rusty Book</a></li><li class="chapter-item expanded affix "><li class="part-title">Awesome</li><li class="spacer"></li><li class="chapter-item expanded "><a href="../daily-dev.html">日常开发常用库</a></li><li class="chapter-item expanded "><a href="../superstar.html">Rust 明星项目</a></li><li class="chapter-item expanded "><a href="../empowering-js.html">使用 Rust 增强 JS</a></li><li class="chapter-item expanded "><a href="../games.html">Rust开发的游戏</a></li><li class="chapter-item expanded "><a href="../gamedev.html">游戏引擎</a></li><li class="chapter-item expanded affix "><li class="part-title">Awesome + Cookbook</li><li class="spacer"></li><li class="chapter-item expanded "><a href="../algos/awesome.html">实用算法</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../algos/randomness.html">生成随机值</a></li><li class="chapter-item expanded "><a href="../algos/sorting.html">Vec 排序</a></li><li class="chapter-item expanded "><div>压缩算法</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../algos/compression/tar.html">使用.tar包</a></li></ol></li><li class="chapter-item expanded "><div>密码学</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../algos/cryptography/hashing.html">哈希</a></li><li class="chapter-item "><a href="../algos/cryptography/encryption.html">加密</a></li></ol></li><li class="chapter-item expanded "><div>数学计算</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../algos/math/linear-algebra.html">线性代数</a></li><li class="chapter-item "><a href="../algos/math/trigonometry.html">三角函数</a></li><li class="chapter-item "><a href="../algos/math/complex.html">复数</a></li><li class="chapter-item "><a href="../algos/math/statistics.html">统计学</a></li><li class="chapter-item "><a href="../algos/math/misc.html">杂项</a></li></ol></li></ol></li><li class="chapter-item expanded "><a href="../datastructures/awesome.html">数据结构</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../datastructures/bitfield.html">位字段</a></li></ol></li><li class="chapter-item expanded "><a href="../cmd/awesome.html">命令行</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../cmd/parsing.html">参数解析</a></li><li class="chapter-item expanded "><a href="../cmd/ansi.html">终端输出格式化</a></li></ol></li><li class="chapter-item expanded "><a href="../os/awesome.html">操作系统</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../os/processor.html">处理器</a></li><li class="chapter-item expanded "><a href="../os/command.html">调用系统命令</a></li></ol></li><li class="chapter-item expanded "><div>并发</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../cocurrency/threads.html" class="active">线程</a></li><li class="chapter-item expanded "><a href="../cocurrency/parallel.html">使用rayon并行处理数据</a></li></ol></li><li class="chapter-item expanded "><div>数据库</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../database/sqlite.html">SQLite</a></li><li class="chapter-item expanded "><a href="../database/postgres.html">Postgres</a></li></ol></li><li class="chapter-item expanded "><div>日期和时间</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../datetime/duration.html">时间计算和转换</a></li><li class="chapter-item expanded "><a href="../datetime/parsing.html">解析和显示</a></li></ol></li><li class="chapter-item expanded "><div>开发者工具</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../devtools/log.html">日志</a></li><li class="chapter-item expanded "><a href="../devtools/config-log.html">配置日志</a></li><li class="chapter-item expanded "><a href="../devtools/version.html">版本号</a></li><li class="chapter-item expanded "><a href="../devtools/build-tools.html">构建时工具</a></li></ol></li><li class="chapter-item expanded "><div>编解码</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../encoding/strings.html">字符编码</a></li><li class="chapter-item expanded "><a href="../encoding/csv.html">CSV</a></li><li class="chapter-item expanded "><a href="../encoding/structured.html">结构化数据</a></li></ol></li><li class="chapter-item expanded "><div>错误处理</div></li><li class="chapter-item expanded "><div>文件操作</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../files/read-write.html">文件读写</a></li><li class="chapter-item expanded "><a href="../files/dir.html">目录访问</a></li></ol></li><li class="chapter-item expanded "><div>内存管理</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../memory/global-vars.html">全局变量</a></li></ol></li><li class="chapter-item expanded "><div>网络协议</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../protocols/tcpip.html">TCP/IP</a></li></ol></li><li class="chapter-item expanded "><div>文本处理</div><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../text/regex.html">正则表达式</a></li><li class="chapter-item expanded "><a href="../text/string.html">字符串解析</a></li></ol></li></ol>
|
|
</div>
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
|
|
</nav>
|
|
|
|
<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 bordered">
|
|
<div class="left-buttons">
|
|
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
<i class="fa fa-bars"></i>
|
|
</button>
|
|
<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 (default)</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">Rusty Book(锈书)</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/studyrs/rusty-book" title="Git repository" aria-label="Git repository">
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
</a>
|
|
<a href="https://github.com/studyrs/rusty-book/edit/main/src/cocurrency/threads.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 type="text/javascript">
|
|
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>
|
|
<h3 id="生成一个临时性的线程"><a class="header" href="#生成一个临时性的线程">生成一个临时性的线程</a></h3>
|
|
<p>下面例子用到了 <a href="cookbook/cocurrency/intro.html">crossbeam</a> 包,它提供了非常实用的、用于并发和并行编程的数据结构和函数。</p>
|
|
<p><a href="https://docs.rs/crossbeam/*/crossbeam/thread/struct.Scope.html#method.spawn">Scope::spawn</a> 会生成一个被限定了作用域的线程,该线程最大的特点就是:它会在传给 <a href="https://docs.rs/crossbeam/0.8.1/crossbeam/fn.scope.html">crossbeam::scope</a> 的闭包函数返回前先行结束。得益于这个特点,子线程的创建使用就像是本地闭包函数调用,因此生成的线程内部可以使用外部环境中的变量!</p>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">fn main() {
|
|
let arr = &[1, 25, -4, 10];
|
|
let max = find_max(arr);
|
|
assert_eq!(max, Some(25));
|
|
}
|
|
|
|
// 将数组分成两个部分,并使用新的线程对它们进行处理
|
|
fn find_max(arr: &[i32]) -> Option<i32> {
|
|
const THRESHOLD: usize = 2;
|
|
|
|
if arr.len() <= THRESHOLD {
|
|
return arr.iter().cloned().max();
|
|
}
|
|
|
|
let mid = arr.len() / 2;
|
|
let (left, right) = arr.split_at(mid);
|
|
|
|
crossbeam::scope(|s| {
|
|
let thread_l = s.spawn(|_| find_max(left));
|
|
let thread_r = s.spawn(|_| find_max(right));
|
|
|
|
let max_l = thread_l.join().unwrap()?;
|
|
let max_r = thread_r.join().unwrap()?;
|
|
|
|
Some(max_l.max(max_r))
|
|
}).unwrap()
|
|
}
|
|
</code></pre></pre>
|
|
<h3 id="创建并行流水线"><a class="header" href="#创建并行流水线">创建并行流水线</a></h3>
|
|
<p>下面我们使用 <a href="https://docs.rs/crossbeam/latest/crossbeam/">crossbeam</a> 和 <a href="https://docs.rs/crossbeam-channel/*/crossbeam_channel/index.html">crossbeam-channel</a> 来创建一个并行流水线:流水线的两端分别是数据源和数据下沉( sink ),在流水线中间,有两个工作线程会从源头接收数据,对数据进行并行处理,最后将数据下沉。</p>
|
|
<ul>
|
|
<li>消息通道( channel )是 <a href="https://docs.rs/crossbeam-channel/0.5.4/crossbeam_channel/fn.bounded.html">crossbeam_channel::bounded</a>,它只能缓存一条消息。当缓存满后,发送者继续调用 [crossbeam_channel::Sender::send] 发送消息时会阻塞,直到一个工作线程( 消费者 ) 拿走这条消息</li>
|
|
<li>消费者获取消息时先到先得的策略,因此两个工作线程只有一个能取到消息,保证消息不会被重复消费、处理</li>
|
|
<li>通过迭代器 <a href="https://docs.rs/crossbeam-channel/*/crossbeam_channel/struct.Receiver.html#method.iter">crossbeam_channel::Receiver::iter</a> 读取消息会阻塞当前线程,直到新消息的到来或 channel 关闭</li>
|
|
<li>channel 只有在所有的发送者或消费者关闭后,才能被关闭。而其中一个消费者 <code>rcv2</code> 处于阻塞读取状态,无比被关闭,因此我们必须要关闭所有发送者: <code>drop(snd1);</code> <code>drop(snd2)</code> ,这样 channel 关闭后,主线程的 <code>rcv2</code> 才能从阻塞状态退出,最后整个程序结束。大家还是迷惑的话,可以看看这篇<a href="https://course.rs/practice/pitfalls/main-with-channel-blocked.html">文章</a>。</li>
|
|
</ul>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">extern crate crossbeam;
|
|
extern crate crossbeam_channel;
|
|
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
use crossbeam_channel::bounded;
|
|
|
|
fn main() {
|
|
let (snd1, rcv1) = bounded(1);
|
|
let (snd2, rcv2) = bounded(1);
|
|
let n_msgs = 4;
|
|
let n_workers = 2;
|
|
|
|
crossbeam::scope(|s| {
|
|
// 生产者线程
|
|
s.spawn(|_| {
|
|
for i in 0..n_msgs {
|
|
snd1.send(i).unwrap();
|
|
println!("Source sent {}", i);
|
|
}
|
|
|
|
// 关闭其中一个发送者 snd1
|
|
// 该关闭操作对于结束最后的循环是必须的
|
|
drop(snd1);
|
|
});
|
|
|
|
// 通过两个线程并行处理
|
|
for _ in 0..n_workers {
|
|
// 从数据源接收数据,然后发送到下沉端
|
|
let (sendr, recvr) = (snd2.clone(), rcv1.clone());
|
|
// 生成单独的工作线程
|
|
s.spawn(move |_| {
|
|
thread::sleep(Duration::from_millis(500));
|
|
// 等待通道的关闭
|
|
for msg in recvr.iter() {
|
|
println!("Worker {:?} received {}.",
|
|
thread::current().id(), msg);
|
|
sendr.send(msg * 2).unwrap();
|
|
}
|
|
});
|
|
}
|
|
// 关闭通道,如果不关闭,下沉端将永远无法结束循环
|
|
drop(snd2);
|
|
|
|
// 下沉端
|
|
for msg in rcv2.iter() {
|
|
println!("Sink received {}", msg);
|
|
}
|
|
}).unwrap();
|
|
}
|
|
</code></pre></pre>
|
|
<h3 id="线程间传递数据"><a class="header" href="#线程间传递数据">线程间传递数据</a></h3>
|
|
<p>下面我们来看看 <a href="https://docs.rs/crossbeam-channel/*/crossbeam_channel/index.html">crossbeam-channel</a> 的单生产者单消费者( SPSC ) 使用场景。</p>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">use std::{thread, time};
|
|
use crossbeam_channel::unbounded;
|
|
|
|
fn main() {
|
|
// unbounded 意味着 channel 可以存储任意多的消息
|
|
let (snd, rcv) = unbounded();
|
|
let n_msgs = 5;
|
|
crossbeam::scope(|s| {
|
|
s.spawn(|_| {
|
|
for i in 0..n_msgs {
|
|
snd.send(i).unwrap();
|
|
thread::sleep(time::Duration::from_millis(100));
|
|
}
|
|
});
|
|
}).unwrap();
|
|
for _ in 0..n_msgs {
|
|
let msg = rcv.recv().unwrap();
|
|
println!("Received {}", msg);
|
|
}
|
|
}
|
|
</code></pre></pre>
|
|
<h3 id="维护全局可变的状态"><a class="header" href="#维护全局可变的状态">维护全局可变的状态</a></h3>
|
|
<p><a href="">lazy_static</a> 会创建一个全局的静态引用( static ref ),该引用使用了 <code>Mutex</code> 以支持可变性,因此我们可以在代码中对其进行修改。<code>Mutex</code> 能保证该全局状态同时只能被一个线程所访问。</p>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">use error_chain::error_chain;
|
|
use lazy_static::lazy_static;
|
|
use std::sync::Mutex;
|
|
|
|
error_chain!{ }
|
|
|
|
lazy_static! {
|
|
static ref FRUIT: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
|
}
|
|
|
|
fn insert(fruit: &str) -> Result<()> {
|
|
let mut db = FRUIT.lock().map_err(|_| "Failed to acquire MutexGuard")?;
|
|
db.push(fruit.to_string());
|
|
Ok(())
|
|
}
|
|
|
|
fn main() -> Result<()> {
|
|
insert("apple")?;
|
|
insert("orange")?;
|
|
insert("peach")?;
|
|
{
|
|
let db = FRUIT.lock().map_err(|_| "Failed to acquire MutexGuard")?;
|
|
|
|
db.iter().enumerate().for_each(|(i, item)| println!("{}: {}", i, item));
|
|
}
|
|
insert("grape")?;
|
|
Ok(())
|
|
}
|
|
</code></pre></pre>
|
|
<h3 id="并行计算-iso-文件的-sha256"><a class="header" href="#并行计算-iso-文件的-sha256">并行计算 iso 文件的 SHA256</a></h3>
|
|
<p>下面的示例将为当前目录中的每一个 .iso 文件都计算一个 SHA256 sum。其中线程池中会初始化和 CPU 核心数一致的线程数,其中核心数是通过 <a href="https://docs.rs/num_cpus/*/num_cpus/fn.get.html">num_cpus::get</a> 函数获取。</p>
|
|
<p><code>Walkdir::new</code> 可以遍历当前的目录,然后调用 <code>execute</code> 来执行读操作和 SHA256 哈希计算。</p>
|
|
<pre><pre class="playground"><code class="language-rust editable edition2021">
|
|
use walkdir::WalkDir;
|
|
use std::fs::File;
|
|
use std::io::{BufReader, Read, Error};
|
|
use std::path::Path;
|
|
use threadpool::ThreadPool;
|
|
use std::sync::mpsc::channel;
|
|
use ring::digest::{Context, Digest, SHA256};
|
|
|
|
// Verify the iso extension
|
|
fn is_iso(entry: &Path) -> bool {
|
|
match entry.extension() {
|
|
Some(e) if e.to_string_lossy().to_lowercase() == "iso" => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
fn compute_digest<P: AsRef<Path>>(filepath: P) -> Result<(Digest, P), Error> {
|
|
let mut buf_reader = BufReader::new(File::open(&filepath)?);
|
|
let mut context = Context::new(&SHA256);
|
|
let mut buffer = [0; 1024];
|
|
|
|
loop {
|
|
let count = buf_reader.read(&mut buffer)?;
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
context.update(&buffer[..count]);
|
|
}
|
|
|
|
Ok((context.finish(), filepath))
|
|
}
|
|
|
|
fn main() -> Result<(), Error> {
|
|
let pool = ThreadPool::new(num_cpus::get());
|
|
|
|
let (tx, rx) = channel();
|
|
|
|
for entry in WalkDir::new("/home/user/Downloads")
|
|
.follow_links(true)
|
|
.into_iter()
|
|
.filter_map(|e| e.ok())
|
|
.filter(|e| !e.path().is_dir() && is_iso(e.path())) {
|
|
let path = entry.path().to_owned();
|
|
let tx = tx.clone();
|
|
pool.execute(move || {
|
|
let digest = compute_digest(path);
|
|
tx.send(digest).expect("Could not send data!");
|
|
});
|
|
}
|
|
|
|
drop(tx);
|
|
for t in rx.iter() {
|
|
let (sha, path) = t?;
|
|
println!("{:?} {:?}", sha, path);
|
|
}
|
|
Ok(())
|
|
}
|
|
</code></pre></pre>
|
|
<h3 id="使用线程池来绘制分形"><a class="header" href="#使用线程池来绘制分形">使用线程池来绘制分形</a></h3>
|
|
<p>下面例子中将基于 <a href="">Julia Set</a> 来绘制一个分形图片,其中使用到了线程池来做分布式计算。</p>
|
|
<img src="https://cloud.githubusercontent.com/assets/221000/26546700/9be34e80-446b-11e7-81dc-dd9871614ea1.png" />
|
|
<pre><pre class="playground"><code class="language-rust edtiable edition2021"><span class="boring">use error_chain::error_chain;
|
|
</span>use std::sync::mpsc::{channel, RecvError};
|
|
use threadpool::ThreadPool;
|
|
use num::complex::Complex;
|
|
use image::{ImageBuffer, Pixel, Rgb};
|
|
|
|
<span class="boring">
|
|
</span><span class="boring">error_chain! {
|
|
</span><span class="boring"> foreign_links {
|
|
</span><span class="boring"> MpscRecv(RecvError);
|
|
</span><span class="boring"> Io(std::io::Error);
|
|
</span><span class="boring"> }
|
|
</span><span class="boring">}
|
|
</span><span class="boring">
|
|
</span><span class="boring">// Function converting intensity values to RGB
|
|
</span><span class="boring">// Based on http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm
|
|
</span><span class="boring">fn wavelength_to_rgb(wavelength: u32) -> Rgb<u8> {
|
|
</span><span class="boring"> let wave = wavelength as f32;
|
|
</span><span class="boring">
|
|
</span><span class="boring"> let (r, g, b) = match wavelength {
|
|
</span><span class="boring"> 380..=439 => ((440. - wave) / (440. - 380.), 0.0, 1.0),
|
|
</span><span class="boring"> 440..=489 => (0.0, (wave - 440.) / (490. - 440.), 1.0),
|
|
</span><span class="boring"> 490..=509 => (0.0, 1.0, (510. - wave) / (510. - 490.)),
|
|
</span><span class="boring"> 510..=579 => ((wave - 510.) / (580. - 510.), 1.0, 0.0),
|
|
</span><span class="boring"> 580..=644 => (1.0, (645. - wave) / (645. - 580.), 0.0),
|
|
</span><span class="boring"> 645..=780 => (1.0, 0.0, 0.0),
|
|
</span><span class="boring"> _ => (0.0, 0.0, 0.0),
|
|
</span><span class="boring"> };
|
|
</span><span class="boring">
|
|
</span><span class="boring"> let factor = match wavelength {
|
|
</span><span class="boring"> 380..=419 => 0.3 + 0.7 * (wave - 380.) / (420. - 380.),
|
|
</span><span class="boring"> 701..=780 => 0.3 + 0.7 * (780. - wave) / (780. - 700.),
|
|
</span><span class="boring"> _ => 1.0,
|
|
</span><span class="boring"> };
|
|
</span><span class="boring">
|
|
</span><span class="boring"> let (r, g, b) = (normalize(r, factor), normalize(g, factor), normalize(b, factor));
|
|
</span><span class="boring"> Rgb::from_channels(r, g, b, 0)
|
|
</span><span class="boring">}
|
|
</span><span class="boring">
|
|
</span><span class="boring">// Maps Julia set distance estimation to intensity values
|
|
</span><span class="boring">fn julia(c: Complex<f32>, x: u32, y: u32, width: u32, height: u32, max_iter: u32) -> u32 {
|
|
</span><span class="boring"> let width = width as f32;
|
|
</span><span class="boring"> let height = height as f32;
|
|
</span><span class="boring">
|
|
</span><span class="boring"> let mut z = Complex {
|
|
</span><span class="boring"> // scale and translate the point to image coordinates
|
|
</span><span class="boring"> re: 3.0 * (x as f32 - 0.5 * width) / width,
|
|
</span><span class="boring"> im: 2.0 * (y as f32 - 0.5 * height) / height,
|
|
</span><span class="boring"> };
|
|
</span><span class="boring">
|
|
</span><span class="boring"> let mut i = 0;
|
|
</span><span class="boring"> for t in 0..max_iter {
|
|
</span><span class="boring"> if z.norm() >= 2.0 {
|
|
</span><span class="boring"> break;
|
|
</span><span class="boring"> }
|
|
</span><span class="boring"> z = z * z + c;
|
|
</span><span class="boring"> i = t;
|
|
</span><span class="boring"> }
|
|
</span><span class="boring"> i
|
|
</span><span class="boring">}
|
|
</span><span class="boring">
|
|
</span><span class="boring">// Normalizes color intensity values within RGB range
|
|
</span><span class="boring">fn normalize(color: f32, factor: f32) -> u8 {
|
|
</span><span class="boring"> ((color * factor).powf(0.8) * 255.) as u8
|
|
</span><span class="boring">}
|
|
</span>
|
|
fn main() -> Result<()> {
|
|
let (width, height) = (1920, 1080);
|
|
// 为指定宽高的输出图片分配内存
|
|
let mut img = ImageBuffer::new(width, height);
|
|
let iterations = 300;
|
|
|
|
let c = Complex::new(-0.8, 0.156);
|
|
|
|
let pool = ThreadPool::new(num_cpus::get());
|
|
let (tx, rx) = channel();
|
|
|
|
for y in 0..height {
|
|
let tx = tx.clone();
|
|
// execute 将每个像素作为单独的作业接收
|
|
pool.execute(move || for x in 0..width {
|
|
let i = julia(c, x, y, width, height, iterations);
|
|
let pixel = wavelength_to_rgb(380 + i * 400 / iterations);
|
|
tx.send((x, y, pixel)).expect("Could not send data!");
|
|
});
|
|
}
|
|
|
|
for _ in 0..(width * height) {
|
|
let (x, y, pixel) = rx.recv()?;
|
|
// 使用数据来设置像素的颜色
|
|
img.put_pixel(x, y, pixel);
|
|
}
|
|
|
|
// 输出图片内容到指定文件中
|
|
let _ = img.save("output.png")?;
|
|
Ok(())
|
|
}
|
|
</code></pre></pre>
|
|
|
|
<div id="giscus-container"></div>
|
|
</main>
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
<!-- Mobile navigation buttons -->
|
|
<a rel="prev" href="../os/command.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" href="../cocurrency/parallel.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="../os/command.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" href="../cocurrency/parallel.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 type="text/javascript">
|
|
window.playground_copyable = true;
|
|
</script>
|
|
<script src="../ace.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../editor.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../mode-rust.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../theme-dawn.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../theme-tomorrow_night.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
|
|
<script src="../book.js" type="text/javascript" charset="utf-8"></script>
|
|
<script type="text/javascript" charset="utf-8">
|
|
var pagePath = "cocurrency/threads.md"
|
|
</script>
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
<script type="text/javascript" src="../assets/custom1.js"></script>
|
|
<script type="text/javascript" src="../assets/bigPicture.js"></script>
|
|
</body>
|
|
</html> |