|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>Rc 与 Arc 实现 1vN 所有权机制 - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
|
|
|
|
|
<meta name="description" content="">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
|
|
|
|
|
|
<link rel="icon" href="../../favicon.svg">
|
|
|
|
|
<link rel="shortcut icon" href="../../favicon.png">
|
|
|
|
|
<link rel="stylesheet" href="../../css/variables.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/general.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/chrome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/print.css" media="print">
|
|
|
|
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
|
|
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../fonts/fonts.css">
|
|
|
|
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../highlight.css">
|
|
|
|
|
<link rel="stylesheet" href="../../tomorrow-night.css">
|
|
|
|
|
<link rel="stylesheet" href="../../ayu-highlight.css">
|
|
|
|
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../theme/style.css">
|
|
|
|
|
|
|
|
|
|
</head>
|
|
|
|
|
<body class="sidebar-visible no-js">
|
|
|
|
|
<div id="body-container">
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script>
|
|
|
|
|
var path_to_root = "../../";
|
|
|
|
|
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
|
|
<script>
|
|
|
|
|
try {
|
|
|
|
|
var theme = localStorage.getItem('mdbook-theme');
|
|
|
|
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
|
|
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script>
|
|
|
|
|
var theme;
|
|
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
html.classList.remove('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
body.classList.remove('no-js')
|
|
|
|
|
body.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script>
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
var sidebar = null;
|
|
|
|
|
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
|
|
sidebar = sidebar || 'visible';
|
|
|
|
|
} else {
|
|
|
|
|
sidebar = 'hidden';
|
|
|
|
|
}
|
|
|
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
|
|
|
body.classList.remove('sidebar-visible');
|
|
|
|
|
body.classList.add("sidebar-" + sidebar);
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
|
|
<div class="sidebar-scrollbox">
|
|
|
|
|
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
<!-- Track and set sidebar scroll position -->
|
|
|
|
|
<script>
|
|
|
|
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
|
|
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|
|
|
|
if (e.target.tagName === 'A') {
|
|
|
|
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
|
|
|
}
|
|
|
|
|
}, { passive: true });
|
|
|
|
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
|
|
|
sessionStorage.removeItem('sidebar-scroll');
|
|
|
|
|
if (sidebarScrollTop) {
|
|
|
|
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|
|
|
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
|
|
|
} else {
|
|
|
|
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
|
|
|
var activeSection = document.querySelector('#sidebar .active');
|
|
|
|
|
if (activeSection) {
|
|
|
|
|
activeSection.scrollIntoView({ block: 'center' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
|
|
|
|
|
|
<div class="page">
|
|
|
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
|
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</label>
|
|
|
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
|
|
|
<i class="fa fa-paint-brush"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
|
|
|
<i class="fa fa-search"></i>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
|
|
|
|
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
|
|
<a href="../../print.html" title="Print this book" aria-label="Print this book">
|
|
|
|
|
<i id="print-button" class="fa fa-print"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
|
|
|
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course/edit/main/src/advance/smart-pointer/rc-arc.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="rc-与-arc"><a class="header" href="#rc-与-arc">Rc 与 Arc</a></h1>
|
|
|
|
|
<p>Rust 所有权机制要求一个值只能有一个所有者,在大多数情况下,都没有问题,但是考虑以下情况:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>在图数据结构中,多个边可能会拥有同一个节点,该节点直到没有边指向它时,才应该被释放清理</li>
|
|
|
|
|
<li>在多线程中,多个线程可能会持有同一个数据,但是你受限于 Rust 的安全机制,无法同时获取该数据的可变引用</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>以上场景不是很常见,但是一旦遇到,就非常棘手,为了解决此类问题,Rust 在所有权机制之外又引入了额外的措施来简化相应的实现:通过引用计数的方式,允许一个数据资源在同一时刻拥有多个所有者。</p>
|
|
|
|
|
<p>这种实现机制就是 <code>Rc</code> 和 <code>Arc</code>,前者适用于单线程,后者适用于多线程。由于二者大部分情况下都相同,因此本章将以 <code>Rc</code> 作为讲解主体,对于 <code>Arc</code> 的不同之处,另外进行单独讲解。</p>
|
|
|
|
|
<h2 id="rct"><a class="header" href="#rct"><code>Rc<T></code></a></h2>
|
|
|
|
|
<p>引用计数(reference counting),顾名思义,通过记录一个数据被引用的次数来确定该数据是否正在被使用。当引用次数归零时,就代表该数据不再被使用,因此可以被清理释放。</p>
|
|
|
|
|
<p>而 <code>Rc</code> 正是引用计数的英文缩写。当我们<strong>希望在堆上分配一个对象供程序的多个部分使用且无法确定哪个部分最后一个结束时,就可以使用 <code>Rc</code> 成为数据值的所有者</strong>,例如之前提到的多线程场景就非常适合。</p>
|
|
|
|
|
<p>下面是经典的所有权被转移导致报错的例子:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let s = String::from("hello, world");
|
|
|
|
|
// s在这里被转移给a
|
|
|
|
|
let a = Box::new(s);
|
|
|
|
|
// 报错!此处继续尝试将 s 转移给 b
|
|
|
|
|
let b = Box::new(s);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>使用 <code>Rc</code> 就可以轻易解决:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::rc::Rc;
|
|
|
|
|
fn main() {
|
|
|
|
|
let a = Rc::new(String::from("hello, world"));
|
|
|
|
|
let b = Rc::clone(&a);
|
|
|
|
|
|
|
|
|
|
assert_eq!(2, Rc::strong_count(&a));
|
|
|
|
|
assert_eq!(Rc::strong_count(&a), Rc::strong_count(&b))
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上代码我们使用 <code>Rc::new</code> 创建了一个新的 <code>Rc<String></code> 智能指针并赋给变量 <code>a</code>,该指针指向底层的字符串数据。</p>
|
|
|
|
|
<p>智能指针 <code>Rc<T></code> 在创建时,还会将引用计数加 1,此时获取引用计数的关联函数 <code>Rc::strong_count</code> 返回的值将是 <code>1</code>。</p>
|
|
|
|
|
<h4 id="rcclone"><a class="header" href="#rcclone">Rc::clone</a></h4>
|
|
|
|
|
<p>接着,我们又使用 <code>Rc::clone</code> 克隆了一份智能指针 <code>Rc<String></code>,并将该智能指针的引用计数增加到 <code>2</code>。</p>
|
|
|
|
|
<p>由于 <code>a</code> 和 <code>b</code> 是同一个智能指针的两个副本,因此通过它们两个获取引用计数的结果都是 <code>2</code>。</p>
|
|
|
|
|
<p>不要被 <code>clone</code> 字样所迷惑,以为所有的 <code>clone</code> 都是深拷贝。这里的 <code>clone</code> <strong>仅仅复制了智能指针并增加了引用计数,并没有克隆底层数据</strong>,因此 <code>a</code> 和 <code>b</code> 是共享了底层的字符串 <code>s</code>,这种<strong>复制效率是非常高</strong>的。当然你也可以使用 <code>a.clone()</code> 的方式来克隆,但是从可读性角度,我们更加推荐 <code>Rc::clone</code> 的方式。</p>
|
|
|
|
|
<p>实际上在 Rust 中,还有不少 <code>clone</code> 都是浅拷贝,例如<a href="https://course.rs/compiler/pitfalls/iterator-everywhere.html">迭代器的克隆</a>。</p>
|
|
|
|
|
<h4 id="观察引用计数的变化"><a class="header" href="#观察引用计数的变化">观察引用计数的变化</a></h4>
|
|
|
|
|
<p>使用关联函数 <code>Rc::strong_count</code> 可以获取当前引用计数的值,我们来观察下引用计数如何随着变量声明、释放而变化:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::rc::Rc;
|
|
|
|
|
fn main() {
|
|
|
|
|
let a = Rc::new(String::from("test ref counting"));
|
|
|
|
|
println!("count after creating a = {}", Rc::strong_count(&a));
|
|
|
|
|
let b = Rc::clone(&a);
|
|
|
|
|
println!("count after creating b = {}", Rc::strong_count(&a));
|
|
|
|
|
{
|
|
|
|
|
let c = Rc::clone(&a);
|
|
|
|
|
println!("count after creating c = {}", Rc::strong_count(&c));
|
|
|
|
|
}
|
|
|
|
|
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>有几点值得注意:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>由于变量 <code>c</code> 在语句块内部声明,当离开语句块时它会因为超出作用域而被释放,所以引用计数会减少 1,事实上这个得益于 <code>Rc<T></code> 实现了 <code>Drop</code> 特征</li>
|
|
|
|
|
<li><code>a</code>、<code>b</code>、<code>c</code> 三个智能指针引用计数都是同样的,并且共享底层的数据,因此打印计数时用哪个都行</li>
|
|
|
|
|
<li>无法看到的是:当 <code>a</code>、<code>b</code> 超出作用域后,引用计数会变成 0,最终智能指针和它指向的底层字符串都会被清理释放</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<h4 id="不可变引用"><a class="header" href="#不可变引用">不可变引用</a></h4>
|
|
|
|
|
<p>事实上,<code>Rc<T></code> 是指向底层数据的不可变的引用,因此你无法通过它来修改数据,这也符合 Rust 的借用规则:要么存在多个不可变借用,要么只能存在一个可变借用。</p>
|
|
|
|
|
<p>但是实际开发中我们往往需要对数据进行修改,这时单独使用 <code>Rc<T></code> 无法满足我们的需求,需要配合其它数据类型来一起使用,例如内部可变性的 <code>RefCell<T></code> 类型以及互斥锁 <code>Mutex<T></code>。事实上,在多线程编程中,<code>Arc</code> 跟 <code>Mutex</code> 锁的组合使用非常常见,它们既可以让我们在不同的线程中共享数据,又允许在各个线程中对其进行修改。</p>
|
|
|
|
|
<h4 id="一个综合例子"><a class="header" href="#一个综合例子">一个综合例子</a></h4>
|
|
|
|
|
<p>考虑一个场景,有很多小工具,每个工具都有自己的主人,但是存在多个工具属于同一个主人的情况,此时使用 <code>Rc<T></code> 就非常适合:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::rc::Rc;
|
|
|
|
|
|
|
|
|
|
struct Owner {
|
|
|
|
|
name: String,
|
|
|
|
|
// ...其它字段
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct Gadget {
|
|
|
|
|
id: i32,
|
|
|
|
|
owner: Rc<Owner>,
|
|
|
|
|
// ...其它字段
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
// 创建一个基于引用计数的 `Owner`.
|
|
|
|
|
let gadget_owner: Rc<Owner> = Rc::new(Owner {
|
|
|
|
|
name: "Gadget Man".to_string(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 创建两个不同的工具,它们属于同一个主人
|
|
|
|
|
let gadget1 = Gadget {
|
|
|
|
|
id: 1,
|
|
|
|
|
owner: Rc::clone(&gadget_owner),
|
|
|
|
|
};
|
|
|
|
|
let gadget2 = Gadget {
|
|
|
|
|
id: 2,
|
|
|
|
|
owner: Rc::clone(&gadget_owner),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 释放掉第一个 `Rc<Owner>`
|
|
|
|
|
drop(gadget_owner);
|
|
|
|
|
|
|
|
|
|
// 尽管在上面我们释放了 gadget_owner,但是依然可以在这里使用 owner 的信息
|
|
|
|
|
// 原因是在 drop 之前,存在三个指向 Gadget Man 的智能指针引用,上面仅仅
|
|
|
|
|
// drop 掉其中一个智能指针引用,而不是 drop 掉 owner 数据,外面还有两个
|
|
|
|
|
// 引用指向底层的 owner 数据,引用计数尚未清零
|
|
|
|
|
// 因此 owner 数据依然可以被使用
|
|
|
|
|
println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
|
|
|
|
|
println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
|
|
|
|
|
|
|
|
|
|
// 在函数最后,`gadget1` 和 `gadget2` 也被释放,最终引用计数归零,随后底层
|
|
|
|
|
// 数据也被清理释放
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>以上代码很好的展示了 <code>Rc<T></code> 的用途,当然你也可以用借用的方式,但是实现起来就会复杂得多,而且随着 <code>Gadget</code> 在代码的各个地方使用,引用生命周期也将变得更加复杂,毕竟结构体中的引用类型,总是令人不那么愉快,对不?</p>
|
|
|
|
|
<h4 id="rc-简单总结"><a class="header" href="#rc-简单总结">Rc 简单总结</a></h4>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>Rc/Arc</code> 是不可变引用,你无法修改它指向的值,只能进行读取,如果要修改,需要配合后面章节的内部可变性 <code>RefCell</code> 或互斥锁 <code>Mutex</code></li>
|
|
|
|
|
<li>一旦最后一个拥有者消失,则资源会自动被回收,这个生命周期是在编译期就确定下来的</li>
|
|
|
|
|
<li><code>Rc</code> 只能用于同一线程内部,想要用于线程之间的对象共享,你需要使用 <code>Arc</code></li>
|
|
|
|
|
<li><code>Rc<T></code> 是一个智能指针,实现了 <code>Deref</code> 特征,因此你无需先解开 <code>Rc</code> 指针,再使用里面的 <code>T</code>,而是可以直接使用 <code>T</code>,例如上例中的 <code>gadget1.owner.name</code></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<h2 id="多线程无力的-rct"><a class="header" href="#多线程无力的-rct">多线程无力的 <code>Rc<T></code></a></h2>
|
|
|
|
|
<p>来看看在多线程场景使用 <code>Rc<T></code> 会如何:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::rc::Rc;
|
|
|
|
|
use std::thread;
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let s = Rc::new(String::from("多线程漫游者"));
|
|
|
|
|
for _ in 0..10 {
|
|
|
|
|
let s = Rc::clone(&s);
|
|
|
|
|
let handle = thread::spawn(move || {
|
|
|
|
|
println!("{}", s)
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>由于我们还没有学习多线程的章节,上面的例子就特地简化了相关的实现。首先通过 <code>thread::spawn</code> 创建一个线程,然后使用 <code>move</code> 关键字把克隆出的 <code>s</code> 的所有权转移到线程中。</p>
|
|
|
|
|
<p>能够实现这一点,完全得益于 <code>Rc</code> 带来的多所有权机制,但是以上代码会报错:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0277]: `Rc<String>` cannot be sent between threads safely
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>表面原因是 <code>Rc<T></code> 不能在线程间安全的传递,实际上是因为它没有实现 <code>Send</code> 特征,而该特征是恰恰是多线程间传递数据的关键,我们会在多线程章节中进行讲解。</p>
|
|
|
|
|
<p>当然,还有更深层的原因:由于 <code>Rc<T></code> 需要管理引用计数,但是该计数器并没有使用任何并发原语,因此无法实现原子化的计数操作,最终会导致计数错误。</p>
|
|
|
|
|
<p>好在天无绝人之路,一起来看看 Rust 为我们提供的功能类似但是多线程安全的 <code>Arc</code>。</p>
|
|
|
|
|
<h2 id="arc"><a class="header" href="#arc">Arc</a></h2>
|
|
|
|
|
<p><code>Arc</code> 是 <code>Atomic Rc</code> 的缩写,顾名思义:原子化的 <code>Rc<T></code> 智能指针。原子化是一种并发原语,我们在后续章节会进行深入讲解,这里你只要知道它能保证我们的数据能够安全的在线程间共享即可。</p>
|
|
|
|
|
<h4 id="arc-的性能损耗"><a class="header" href="#arc-的性能损耗">Arc 的性能损耗</a></h4>
|
|
|
|
|
<p>你可能好奇,为何不直接使用 <code>Arc</code>,还要画蛇添足弄一个 <code>Rc</code>,还有 Rust 的基本数据类型、标准库数据类型为什么不自动实现原子化操作?这样就不存在线程不安全的问题了。</p>
|
|
|
|
|
<p>原因在于原子化或者其它锁虽然可以带来的线程安全,但是都会伴随着性能损耗,而且这种性能损耗还不小。因此 Rust 把这种选择权交给你,毕竟需要线程安全的代码其实占比并不高,大部分时候我们开发的程序都在一个线程内。</p>
|
|
|
|
|
<p><code>Arc</code> 和 <code>Rc</code> 拥有完全一样的 API,修改起来很简单:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::sync::Arc;
|
|
|
|
|
use std::thread;
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let s = Arc::new(String::from("多线程漫游者"));
|
|
|
|
|
for _ in 0..10 {
|
|
|
|
|
let s = Arc::clone(&s);
|
|
|
|
|
let handle = thread::spawn(move || {
|
|
|
|
|
println!("{}", s)
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>对了,两者还有一点区别:<code>Arc</code> 和 <code>Rc</code> 并没有定义在同一个模块,前者通过 <code>use std::sync::Arc</code> 来引入,后者通过 <code>use std::rc::Rc</code>。</p>
|
|
|
|
|
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
|
|
|
|
|
<p>在 Rust 中,所有权机制保证了一个数据只会有一个所有者,但如果你想要在图数据结构、多线程等场景中共享数据,这种机制会成为极大的阻碍。好在 Rust 为我们提供了智能指针 <code>Rc</code> 和 <code>Arc</code>,使用它们就能实现多个所有者共享一个数据的功能。</p>
|
|
|
|
|
<p><code>Rc</code> 和 <code>Arc</code> 的区别在于,后者是原子化实现的引用计数,因此是线程安全的,可以用于多线程中共享数据。</p>
|
|
|
|
|
<p>这两者都是只读的,如果想要实现内部数据可修改,必须配合内部可变性 <code>RefCell</code> 或者互斥锁 <code>Mutex</code> 来一起使用。</p>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../advance/smart-pointer/drop.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/smart-pointer/cell-refcell.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/smart-pointer/drop.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/smart-pointer/cell-refcell.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/smart-pointer/rc-arc.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|