<!DOCTYPE HTML>
< html lang = "zh-CN" class = "light sidebar-visible" dir = "ltr" >
< head >
<!-- Book generated using mdBook -->
< meta charset = "UTF-8" >
< title > 线程同步: 锁、Condvar 和信号量 - 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-de23e50b.svg" >
< link rel = "shortcut icon" href = "../../favicon-8114d1fc.png" >
< link rel = "stylesheet" href = "../../css/variables-8adf115d.css" >
< link rel = "stylesheet" href = "../../css/general-2459343d.css" >
< link rel = "stylesheet" href = "../../css/chrome-ae938929.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 = "../../theme/style-234bffbf.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-848c21ce.js";
< / script >
<!-- Start loading toc.js asap -->
< script src = "../../toc-42887675.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" > Rust语言圣经(Rust Course)< / 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/sunface/rust-course" 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 >
< a href = "https://github.com/sunface/rust-course/edit/main/src/advance/concurrency-with-threads/sync1.md" title = "Suggest an edit" aria-label = "Suggest an edit" rel = "edit" >
< span class = fa-svg id = "git-edit-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 = "M421.7 220.3l-11.3 11.3-22.6 22.6-205 205c-6.6 6.6-14.8 11.5-23.8 14.1L30.8 511c-8.4 2.5-17.5 .2-23.7-6.1S-1.5 489.7 1 481.2L38.7 353.1c2.6-9 7.5-17.2 14.1-23.8l205-205 22.6-22.6 11.3-11.3 33.9 33.9 62.1 62.1 33.9 33.9zM96 353.9l-9.3 9.3c-.9 .9-1.6 2.1-2 3.4l-25.3 86 86-25.3c1.3-.4 2.5-1.1 3.4-2l9.3-9.3H112c-8.8 0-16-7.2-16-16V353.9zM453.3 19.3l39.4 39.4c25 25 25 65.5 0 90.5l-14.5 14.5-22.6 22.6-11.3 11.3-33.9-33.9-62.1-62.1L314.3 67.7l11.3-11.3 22.6-22.6 14.5-14.5c25-25 65.5-25 90.5 0z" / > < / 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 >
< h1 id = "线程同步锁condvar-和信号量" > < a class = "header" href = "#线程同步锁condvar-和信号量" > 线程同步: 锁、Condvar 和信号量< / a > < / h1 >
< p > 在多线程编程中,同步性极其的重要,当你需要同时访问一个资源、控制不同线程的执行次序时,都需要使用到同步性。< / p >
< p > 在 Rust 中有多种方式可以实现同步性。在上一节中讲到的消息传递就是同步性的一种实现方式,例如我们可以通过消息传递来控制不同线程间的执行次序。还可以使用共享内存来实现同步性,例如通过锁和原子操作等并发原语来实现多个线程同时且安全地去访问一个资源。< / p >
< h2 id = "该如何选择" > < a class = "header" href = "#该如何选择" > 该如何选择< / a > < / h2 >
< p > 共享内存可以说是同步的灵魂,因为消息传递的底层实际上也是通过共享内存来实现,两者的区别如下:< / p >
< ul >
< li > 共享内存相对消息传递能节省多次内存拷贝的成本< / li >
< li > 共享内存的实现简洁的多< / li >
< li > 共享内存的锁竞争更多< / li >
< / ul >
< p > 消息传递适用的场景很多,我们下面列出了几个主要的使用场景:< / p >
< ul >
< li > 需要可靠和简单的(简单不等于简洁)实现时< / li >
< li > 需要模拟现实世界,例如用消息去通知某个目标执行相应的操作时< / li >
< li > 需要一个任务处理流水线(管道)时,等等< / li >
< / ul >
< p > 而使用共享内存(并发原语)的场景往往就比较简单粗暴:需要简洁的实现以及更高的性能时。< / p >
< p > 总之,消息传递类似一个单所有权的系统:一个值同时只能有一个所有者,如果另一个线程需要该值的所有权,需要将所有权通过消息传递进行转移。而共享内存类似于一个多所有权的系统:多个线程可以同时访问同一个值。< / p >
< h2 id = "互斥锁-mutex" > < a class = "header" href = "#互斥锁-mutex" > 互斥锁 Mutex< / a > < / h2 >
< p > 既然是共享内存,那并发原语自然是重中之重,先来一起看看皇冠上的明珠: 互斥锁< code > Mutex< / code > (mutual exclusion 的缩写)。< / p >
< p > < code > Mutex< / code > 让多个线程并发的访问同一个值变成了排队访问:同一时间,只允许一个线程< code > A< / code > 访问该值,其它线程需要等待< code > A< / code > 访问完成后才能继续。< / p >
< h4 id = "单线程中使用-mutex" > < a class = "header" href = "#单线程中使用-mutex" > 单线程中使用 Mutex< / a > < / h4 >
< p > 先来看看单线程中< code > Mutex< / code > 该如何使用:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::Mutex;
fn main() {
// 使用`Mutex`结构体的关联函数创建新的互斥锁实例
let m = Mutex::new(5);
{
// 获取锁, 然后deref为`m`的引用
// lock返回的是Result
let mut num = m.lock().unwrap();
*num = 6;
// 锁自动被drop
}
println!("m = {:?}", m);
}< / code > < / pre >
< p > 在注释中,已经大致描述了代码的功能,不过有一点需要注意:和< code > Box< / code > 类似,数据被< code > Mutex< / code > 所拥有,要访问内部的数据,需要使用方法< code > m.lock()< / code > 向< code > m< / code > 申请一个锁, 该方法会< strong > 阻塞当前线程,直到获取到锁< / strong > ,因此当多个线程同时访问该数据时,只有一个线程能获取到锁,其它线程只能阻塞着等待,这样就保证了数据能被安全的修改!< / p >
< p > < strong > < code > m.lock()< / code > 方法也有可能报错< / strong > ,例如当前正在持有锁的线程< code > panic< / code > 了。在这种情况下,其它线程不可能再获得锁,因此< code > lock< / code > 方法会返回一个错误。< / p >
< p > 这里你可能奇怪,< code > m.lock< / code > 明明返回一个锁,怎么就变成我们的< code > num< / code > 数值了?聪明的读者可能会想到智能指针,没错,因为< code > Mutex< T> < / code > 是一个智能指针,准确的说是< code > m.lock()< / code > 返回一个智能指针< code > MutexGuard< T> < / code > :< / p >
< ul >
< li > 它实现了< code > Deref< / code > 特征,会被自动解引用后获得一个引用类型,该引用指向< code > Mutex< / code > 内部的数据< / li >
< li > 它还实现了< code > Drop< / code > 特征,在超出作用域后,自动释放锁,以便其它线程能继续获取锁< / li >
< / ul >
< p > 正因为智能指针的使用,使得我们无需任何操作就能获取其中的数据。 如果释放锁,你需要做的仅仅是做好锁的作用域管理,例如上述代码的内部花括号使用,建议读者尝试下去掉内部的花括号,然后再次尝试获取第二个锁< code > num1< / code > ,看看会发生什么,友情提示:不会报错,但是主线程会永远阻塞,因为不幸发生了死锁。< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
let mut num = m.lock().unwrap();
*num = 6;
// 锁还没有被 drop 就尝试申请下一个锁,导致主线程阻塞
// drop(num); // 手动 drop num ,可以让 num1 申请到下个锁
let mut num1 = m.lock().unwrap();
*num1 = 7;
// drop(num1); // 手动 drop num1 ,观察打印结果的不同
println!("m = {:?}", m);
}< / code > < / pre >
< h4 id = "多线程中使用-mutex" > < a class = "header" href = "#多线程中使用-mutex" > 多线程中使用 Mutex< / a > < / h4 >
< p > 单线程中使用锁,说实话纯粹是为了演示功能,毕竟多线程才是锁的舞台。 现在,我们再来看看,如何在多线程下使用< code > Mutex< / code > 来访问同一个资源.< / p >
< h5 id = "无法运行的rct" > < a class = "header" href = "#无法运行的rct" > 无法运行的< code > Rc< T> < / code > < / a > < / h5 >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
// 通过`Rc`实现`Mutex`的多所有权
let counter = Rc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Rc::clone(& counter);
// 创建子线程,并将`Mutex`的所有权拷贝传入到子线程中
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
// 等待所有子线程完成
for handle in handles {
handle.join().unwrap();
}
// 输出最终的计数结果
println!("Result: {}", *counter.lock().unwrap());
}< / code > < / pre >
< p > 由于子线程需要通过< code > move< / code > 拿走锁的所有权,因此我们需要使用多所有权来保证每个线程都拿到数据的独立所有权,恰好智能指针< a href = "https://course.rs/advance/smart-pointer/rc-arc.html" > < code > Rc< T> < / code > < / a > 可以做到(< strong > 上面代码会报错< / strong > !具体往下看,别跳过-, -)。< / p >
< p > 以上代码实现了在多线程中计数的功能,由于多个线程都需要去修改该计数器,因此我们需要使用锁来保证同一时间只有一个线程可以修改计数器,否则会导致脏数据:想象一下 A 线程和 B 线程同时拿到计数器,获取了当前值< code > 1< / code > , 并且同时对其进行了修改,最后值变成< code > 2< / code > ,你会不会在风中凌乱?毕竟正确的值是< code > 3< / code > ,因为两个线程各自加 1。< / p >
< p > 可能有人会说,有那么巧的事情吗?事实上,对于人类来说,因为干啥啥慢,并没有那么多巧合,所以人总会存在巧合心理。但是对于计算机而言,每秒可以轻松运行上亿次,在这种频次下,一切巧合几乎都将必然发生,因此千万不要有任何侥幸心理。< / p >
< blockquote >
< p > 如果事情有变坏的可能,不管这种可能性有多小,它都会发生! - 在计算机领域歪打正着的墨菲定律< / p >
< / blockquote >
< p > 事实上,上面的代码会报错:< / p >
< pre > < code class = "language-console" > error[E0277]: `Rc< Mutex< i32> > ` cannot be sent between threads safely
// `Rc`无法在线程中安全的传输
--> src/main.rs:11:22
|
13 | let handle = thread::spawn(move || {
| ______________________^^^^^^^^^^^^^_-
| | |
| | `Rc< Mutex< i32> > ` cannot be sent between threads safely
14 | | let mut num = counter.lock().unwrap();
15 | |
16 | | *num += 1;
17 | | });
| |_________- within this `[closure@src/main.rs:11:36: 15:10]`
|
= help: within `[closure@src/main.rs:11:36: 15:10]`, the trait `Send` is not implemented for `Rc< Mutex< i32> > `
// `Rc`没有实现`Send`特征
= note: required because it appears within the type `[closure@src/main.rs:11:36: 15:10]`
< / code > < / pre >
< p > 错误中提到了一个关键点:< code > Rc< T> < / code > 无法在线程中传输,因为它没有实现< code > Send< / code > 特征(在下一节将详细介绍),而该特征可以确保数据在线程中安全的传输。< / p >
< h5 id = "多线程安全的-arct" > < a class = "header" href = "#多线程安全的-arct" > 多线程安全的 < code > Arc< T> < / code > < / a > < / h5 >
< p > 好在,我们有< code > Arc< T> < / code > ,得益于它的< a href = "https://course.rs/advance/smart-pointer/rc-arc.html#多线程无力的rc" > 内部计数器< / a > 是多线程安全的,因此可以在多线程环境中使用:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(& counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}< / code > < / pre >
< p > 以上代码可以顺利运行:< / p >
< pre > < code class = "language-console" > Result: 10
< / code > < / pre >
< h4 id = "内部可变性" > < a class = "header" href = "#内部可变性" > 内部可变性< / a > < / h4 >
< p > 在之前章节,我们提到过< a href = "https://course.rs/advance/smart-pointer/cell-refcell.html#内部可变性" > 内部可变性< / a > ,其中< code > Rc< T> < / code > 和< code > RefCell< T> < / code > 的结合,可以实现单线程的内部可变性。< / p >
< p > 现在我们又有了新的武器,由于< code > Mutex< T> < / code > 可以支持修改内部数据,当结合< code > Arc< T> < / code > 一起使用时,可以实现多线程的内部可变性。< / p >
< p > 简单总结下:< code > Rc< T> /RefCell< T> < / code > 用于单线程内部可变性, < code > Arc< T> /Mutex< T> < / code > 用于多线程内部可变性。< / p >
< h4 id = "需要小心使用的-mutex" > < a class = "header" href = "#需要小心使用的-mutex" > 需要小心使用的 Mutex< / a > < / h4 >
< p > 如果有其它语言的编程经验,就知道互斥锁这家伙不好对付,想要正确使用,你得牢记在心:< / p >
< ul >
< li > 在使用数据前必须先获取锁< / li >
< li > 在数据使用完成后,必须< strong > 及时< / strong > 的释放锁,比如文章开头的例子,使用内部语句块的目的就是为了及时的释放锁< / li >
< / ul >
< p > 这两点看起来不起眼,但要正确的使用,其实是相当不简单的,对于其它语言,忘记释放锁是经常发生的,虽然 Rust 通过智能指针的< code > drop< / code > 机制帮助我们避免了这一点,但是由于不及时释放锁导致的性能问题也是常见的。< / p >
< p > 正因为这种困难性,导致很多用户都热衷于使用消息传递的方式来实现同步,例如 Go 语言直接把< code > channel< / code > 内置在语言特性中,甚至还有无锁的语言,例如< code > erlang< / code > ,完全使用< code > Actor< / code > 模型,依赖消息传递来完成共享和同步。幸好 Rust 的类型系统、所有权机制、智能指针等可以很好的帮助我们减轻使用锁时的负担。< / p >
< p > 另一个值得注意的是在使用< code > Mutex< T> < / code > 时, Rust 无法帮我们避免所有的逻辑错误,例如在之前章节,我们提到过使用< code > Rc< T> < / code > 可能会导致< a href = "https://course.rs/advance/circle-self-ref/circle-reference.html" > 循环引用的问题< / a > 。类似的,< code > Mutex< T> < / code > 也存在使用上的风险,例如创建死锁(deadlock):当一个操作试图锁住两个资源,然后两个线程各自获取其中一个锁,并试图获取另一个锁时,就会造成死锁。< / p >
< h2 id = "死锁" > < a class = "header" href = "#死锁" > 死锁< / a > < / h2 >
< p > 在 Rust 中有多种方式可以创建死锁,了解这些方式有助于你提前规避可能的风险,一起来看看。< / p >
< h4 id = "单线程死锁" > < a class = "header" href = "#单线程死锁" > 单线程死锁< / a > < / h4 >
< p > 这种死锁比较容易规避,但是当代码复杂后还是有可能遇到:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::Mutex;
fn main() {
let data = Mutex::new(0);
let d1 = data.lock();
let d2 = data.lock();
} // d1锁在此处释放< / code > < / pre >
< p > 非常简单,只要你在另一个锁还未被释放时去申请新的锁,就会触发,当代码复杂后,这种情况可能就没有那么显眼。< / p >
< h4 id = "多线程死锁" > < a class = "header" href = "#多线程死锁" > 多线程死锁< / a > < / h4 >
< p > 当我们拥有两个锁,且两个线程各自使用了其中一个锁,然后试图去访问另一个锁时,就可能发生死锁:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::{sync::{Mutex, MutexGuard}, thread};
use std::thread::sleep;
use std::time::Duration;
use lazy_static::lazy_static;
lazy_static! {
static ref MUTEX1: Mutex< i64> = Mutex::new(0);
static ref MUTEX2: Mutex< i64> = Mutex::new(0);
}
fn main() {
// 存放子线程的句柄
let mut children = vec![];
for i_thread in 0..2 {
children.push(thread::spawn(move || {
for _ in 0..1 {
// 线程1
if i_thread % 2 == 0 {
// 锁住MUTEX1
let guard: MutexGuard< i64> = MUTEX1.lock().unwrap();
println!("线程 {} 锁住了MUTEX1, 接着准备去锁MUTEX2 !", i_thread);
// 当前线程睡眠一小会儿, 等待线程2锁住MUTEX2
sleep(Duration::from_millis(10));
// 去锁MUTEX2
let guard = MUTEX2.lock().unwrap();
// 线程2
} else {
// 锁住MUTEX2
let _guard = MUTEX2.lock().unwrap();
println!("线程 {} 锁住了MUTEX2, 准备去锁MUTEX1", i_thread);
let _guard = MUTEX1.lock().unwrap();
}
}
}));
}
// 等子线程完成
for child in children {
let _ = child.join();
}
println!("死锁没有发生");
}< / code > < / pre >
< p > 在上面的描述中,我们用了“可能“二字,原因在于死锁在这段代码中不是必然发生的,总有一次运行你能看到最后一行打印输出。这是由于子线程的初始化顺序和执行速度并不确定,我们无法确定哪个线程中的锁先被执行,因此也无法确定两个线程对锁的具体使用顺序。< / p >
< p > 但是,可以简单的说明下死锁发生的必然条件:线程 1 锁住了< code > MUTEX1< / code > 并且线程< code > 2< / code > 锁住了< code > MUTEX2< / code > ,然后线程 1 试图去访问< code > MUTEX2< / code > ,同时线程< code > 2< / code > 试图去访问< code > MUTEX1< / code > ,就会死锁。 因为线程 2 需要等待线程 1 释放< code > MUTEX1< / code > 后,才会释放< code > MUTEX2< / code > ,而与此同时,线程 1 需要等待线程 2 释放< code > MUTEX2< / code > 后才能释放< code > MUTEX1< / code > ,这种情况造成了两个线程都无法释放对方需要的锁,最终死锁。< / p >
< p > 那么为何某些时候,死锁不会发生?原因很简单,线程 2 在线程 1 锁< code > MUTEX1< / code > 之前,就已经全部执行完了,随之线程 2 的< code > MUTEX2< / code > 和< code > MUTEX1< / code > 被全部释放,线程 1 对锁的获取将不再有竞争者。 同理,线程 1 若全部被执行完,那线程 2 也不会被锁,因此我们在线程 1 中间加一个睡眠,增加死锁发生的概率。如果你在线程 2 中同样的位置也增加一个睡眠,那死锁将必然发生!< / p >
< h4 id = "try_lock" > < a class = "header" href = "#try_lock" > try_lock< / a > < / h4 >
< p > 与< code > lock< / code > 方法不同,< code > try_lock< / code > 会< strong > 尝试< / strong > 去获取一次锁,如果无法获取会返回一个错误,因此< strong > 不会发生阻塞< / strong > :< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::{sync::{Mutex, MutexGuard}, thread};
use std::thread::sleep;
use std::time::Duration;
use lazy_static::lazy_static;
lazy_static! {
static ref MUTEX1: Mutex< i64> = Mutex::new(0);
static ref MUTEX2: Mutex< i64> = Mutex::new(0);
}
fn main() {
// 存放子线程的句柄
let mut children = vec![];
for i_thread in 0..2 {
children.push(thread::spawn(move || {
for _ in 0..1 {
// 线程1
if i_thread % 2 == 0 {
// 锁住MUTEX1
let guard: MutexGuard< i64> = MUTEX1.lock().unwrap();
println!("线程 {} 锁住了MUTEX1, 接着准备去锁MUTEX2 !", i_thread);
// 当前线程睡眠一小会儿, 等待线程2锁住MUTEX2
sleep(Duration::from_millis(10));
// 去锁MUTEX2
let guard = MUTEX2.try_lock();
println!("线程 {} 获取 MUTEX2 锁的结果: {:?}", i_thread, guard);
// 线程2
} else {
// 锁住MUTEX2
let _guard = MUTEX2.lock().unwrap();
println!("线程 {} 锁住了MUTEX2, 准备去锁MUTEX1", i_thread);
sleep(Duration::from_millis(10));
let guard = MUTEX1.try_lock();
println!("线程 {} 获取 MUTEX1 锁的结果: {:?}", i_thread, guard);
}
}
}));
}
// 等子线程完成
for child in children {
let _ = child.join();
}
println!("死锁没有发生");
}< / code > < / pre >
< p > 为了演示< code > try_lock< / code > 的作用,我们特定使用了之前必定会死锁的代码,并且将< code > lock< / code > 替换成< code > try_lock< / code > ,与之前的结果不同,这段代码将不会再有死锁发生:< / p >
< pre > < code class = "language-console" > 线程 0 锁住了MUTEX1, 接着准备去锁MUTEX2 !
线程 1 锁住了MUTEX2, 准备去锁MUTEX1
线程 1 获取 MUTEX1 锁的结果: Err("WouldBlock")
线程 0 获取 MUTEX2 锁的结果: Ok(0)
死锁没有发生
< / code > < / pre >
< p > 如上所示,当< code > try_lock< / code > 失败时,会报出一个错误:< code > Err("WouldBlock")< / code > ,接着线程中的剩余代码会继续执行,不会被阻塞。< / p >
< blockquote >
< p > 一个有趣的命名规则:在 Rust 标准库中,使用< code > try_xxx< / code > 都会尝试进行一次操作,如果无法完成,就立即返回,不会发生阻塞。例如消息传递章节中的< code > try_recv< / code > 以及本章节中的< code > try_lock< / code > < / p >
< / blockquote >
< h2 id = "读写锁-rwlock" > < a class = "header" href = "#读写锁-rwlock" > 读写锁 RwLock< / a > < / h2 >
< p > < code > Mutex< / code > 会对每次读写都进行加锁,但某些时候,我们需要大量的并发读,< code > Mutex< / code > 就无法满足需求了,此时就可以使用< code > RwLock< / code > :< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::RwLock;
fn main() {
let lock = RwLock::new(5);
// 同一时间允许多个读
{
let r1 = lock.read().unwrap();
let r2 = lock.read().unwrap();
assert_eq!(*r1, 5);
assert_eq!(*r2, 5);
} // 读锁在此处被drop
// 同一时间只允许一个写
{
let mut w = lock.write().unwrap();
*w += 1;
assert_eq!(*w, 6);
// 以下代码会阻塞发生死锁,因为读和写不允许同时存在
// 写锁w直到该语句块结束才被释放, 因此下面的读锁依然处于`w`的作用域中
// let r1 = lock.read();
// println!("{:?}",r1);
}// 写锁在此处被drop
}< / code > < / pre >
< p > < code > RwLock< / code > 在使用上和< code > Mutex< / code > 区别不大,只有在多个读的情况下不阻塞程序,其他如读写、写读、写写情况下均会对后获取锁的操作进行阻塞。< / p >
< p > 我们也可以使用< code > try_write< / code > 和< code > try_read< / code > 来尝试进行一次写/读,若失败则返回错误:< / p >
< pre > < code class = "language-console" > Err("WouldBlock")
< / code > < / pre >
< p > 简单总结下< code > RwLock< / code > :< / p >
< ol >
< li > 同时允许多个读,但最多只能有一个写< / li >
< li > 读和写不能同时存在< / li >
< li > 读可以使用< code > read< / code > 、< code > try_read< / code > ,写< code > write< / code > 、< code > try_write< / code > , 在实际项目中,< code > try_xxx< / code > 会安全的多< / li >
< / ol >
< h2 id = "mutex-还是-rwlock" > < a class = "header" href = "#mutex-还是-rwlock" > Mutex 还是 RwLock< / a > < / h2 >
< p > 首先简单性上< code > Mutex< / code > 完胜,因为使用< code > RwLock< / code > 你得操心几个问题:< / p >
< ul >
< li > 读和写不能同时发生,如果使用< code > try_xxx< / code > 解决,就必须做大量的错误处理和失败重试机制< / li >
< li > 当读多写少时,写操作可能会因为一直无法获得锁导致连续多次失败(< a href = "https://stackoverflow.com/questions/2190090/how-to-prevent-writer-starvation-in-a-read-write-lock-in-pthreads" > writer starvation< / a > )< / li >
< li > RwLock 其实是操作系统提供的,实现原理要比< code > Mutex< / code > 复杂的多,因此单就锁的性能而言,比不上原生实现的< code > Mutex< / code > < / li >
< / ul >
< p > 再来简单总结下两者的使用场景:< / p >
< ul >
< li > 追求高并发读取时,使用< code > RwLock< / code > ,因为< code > Mutex< / code > 一次只允许一个线程去读取< / li >
< li > 如果要保证写操作的成功性,使用< code > Mutex< / code > < / li >
< li > 不知道哪个合适,统一使用< code > Mutex< / code > < / li >
< / ul >
< p > 需要注意的是,< code > RwLock< / code > 虽然看上去貌似提供了高并发读取的能力,但这个不能说明它的性能比< code > Mutex< / code > 高,事实上< code > Mutex< / code > 性能要好不少,后者< strong > 唯一的问题也仅仅在于不能并发读取< / strong > 。< / p >
< p > 一个常见的、错误的使用< code > RwLock< / code > 的场景就是使用< code > HashMap< / code > 进行简单读写,因为< code > HashMap< / code > 的读和写都非常快,< code > RwLock< / code > 的复杂实现和相对低的性能反而会导致整体性能的降低,因此一般来说更适合使用< code > Mutex< / code > 。< / p >
< p > 总之,如果你要使用< code > RwLock< / code > 要确保满足以下两个条件:< strong > 并发读,且需要对读到的资源进行“长时间“的操作< / strong > , < code > HashMap< / code > 也许满足了并发读的需求,但是往往并不能满足后者:“长时间“的操作。< / p >
< blockquote >
< p > benchmark 永远是你在迷茫时最好的朋友!< / p >
< / blockquote >
< h2 id = "三方库提供的锁实现" > < a class = "header" href = "#三方库提供的锁实现" > 三方库提供的锁实现< / a > < / h2 >
< p > 标准库在设计时总会存在取舍,因为往往性能并不是最好的,如果你追求性能,可以使用三方库提供的并发原语:< / p >
< ul >
< li > < a href = "https://crates.io/crates/parking_lot" > parking_lot< / a > , 功能更完善、稳定, 社区较为活跃, star 较多,更新较为活跃< / li >
< li > < a href = "https://crates.io/crates/spin" > spin< / a > , 在多数场景中性能比< code > parking_lot< / code > 高一点,最近没怎么更新< / li >
< / ul >
< p > 如果不是追求特别极致的性能,建议选择前者。< / p >
< h2 id = "用条件变量condvar控制线程的同步" > < a class = "header" href = "#用条件变量condvar控制线程的同步" > 用条件变量(Condvar)控制线程的同步< / a > < / h2 >
< p > < code > Mutex< / code > 用于解决资源安全访问的问题,但是我们还需要一个手段来解决资源访问顺序的问题。而 Rust 考虑到了这一点,为我们提供了条件变量(Condition Variables),它经常和< code > Mutex< / code > 一起使用,可以让线程挂起,直到某个条件发生后再继续执行,其实< code > Condvar< / code > 我们在之前的多线程章节就已经见到过,现在再来看一个不同的例子:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::{Arc,Mutex,Condvar};
use std::thread::{spawn,sleep};
use std::time::Duration;
fn main() {
let flag = Arc::new(Mutex::new(false));
let cond = Arc::new(Condvar::new());
let cflag = flag.clone();
let ccond = cond.clone();
let hdl = spawn(move || {
let mut lock = cflag.lock().unwrap();
let mut counter = 0;
while counter < 3 {
while !*lock {
// wait方法会接收一个MutexGuard< 'a, T> ,且它会自动地暂时释放这个锁,使其他线程可以拿到锁并进行数据更新。
// 同时当前线程在此处会被阻塞, 直到被其他地方notify后, 它会将原本的MutexGuard< 'a, T> 还给我们,即重新获取到了锁,同时唤醒了此线程。
lock = ccond.wait(lock).unwrap();
}
*lock = false;
counter += 1;
println!("inner counter: {}", counter);
}
});
let mut counter = 0;
loop {
sleep(Duration::from_millis(1000));
*flag.lock().unwrap() = true;
counter += 1;
if counter > 3 {
break;
}
println!("outside counter: {}", counter);
cond.notify_one();
}
hdl.join().unwrap();
println!("{:?}", flag);
}< / code > < / pre >
< p > 例子中通过主线程来触发子线程实现交替打印输出:< / p >
< pre > < code class = "language-console" > outside counter: 1
inner counter: 1
outside counter: 2
inner counter: 2
outside counter: 3
inner counter: 3
Mutex { data: true, poisoned: false, .. }
< / code > < / pre >
< h2 id = "信号量-semaphore" > < a class = "header" href = "#信号量-semaphore" > 信号量 Semaphore< / a > < / h2 >
< p > 在多线程中,另一个重要的概念就是信号量,使用它可以让我们精准的控制当前正在运行的任务最大数量。想象一下,当一个新游戏刚开服时(有些较火的老游戏也会,比如< code > wow< / code > ),往往会控制游戏内玩家的同时在线数,一旦超过某个临界值,就开始进行排队进服。而在实际使用中,也有很多时候,我们需要通过信号量来控制最大并发数,防止服务器资源被撑爆。< / p >
< p > 本来 Rust 在标准库中有提供一个< a href = "https://doc.rust-lang.org/1.8.0/std/sync/struct.Semaphore.html" > 信号量实现< / a > , 但是由于各种原因这个库现在已经不再推荐使用了,因此我们推荐使用< code > tokio< / code > 中提供的< code > Semaphore< / code > 实现: < a href = "https://github.com/tokio-rs/tokio/blob/master/tokio/src/sync/semaphore.rs" > < code > tokio::sync::Semaphore< / code > < / a > 。< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::sync::Arc;
use tokio::sync::Semaphore;
#[tokio::main]
async fn main() {
let semaphore = Arc::new(Semaphore::new(3));
let mut join_handles = Vec::new();
for _ in 0..5 {
let permit = semaphore.clone().acquire_owned().await.unwrap();
join_handles.push(tokio::spawn(async move {
//
// 在这里执行任务...
//
drop(permit);
}));
}
for handle in join_handles {
handle.await.unwrap();
}
}< / code > < / pre >
< p > 上面代码创建了一个容量为 3 的信号量,当正在执行的任务超过 3 时,剩下的任务需要等待正在执行任务完成并减少信号量后到 3 以内时,才能继续执行。< / p >
< p > 这里的关键其实说白了就在于:信号量的申请和归还,使用前需要申请信号量,如果容量满了,就需要等待;使用后需要释放信号量,以便其它等待者可以继续。< / p >
< h2 id = "总结" > < a class = "header" href = "#总结" > 总结< / a > < / h2 >
< p > 在很多时候,消息传递都是非常好用的手段,它可以让我们的数据在任务流水线上不断流转,实现起来非常优雅。< / p >
< p > 但是它并不能优雅的解决所有问题,因为我们面临的真实世界是非常复杂的,无法用某一种银弹统一解决。当面临消息传递不太适用的场景时,或者需要更好的性能和简洁性时,我们往往需要用锁来解决这些问题,因为锁允许多个线程同时访问同一个资源,简单粗暴。< / p >
< p > 除了锁之外,其实还有一种并发原语可以帮助我们解决并发访问数据的问题,那就是原子类型 Atomic, 在下一章节中, 我们会对其进行深入讲解。< / p >
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
< a rel = "prev" href = "../../advance/concurrency-with-threads/message-passing.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 = "../../advance/concurrency-with-threads/sync2.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 = "../../advance/concurrency-with-threads/message-passing.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 = "../../advance/concurrency-with-threads/sync2.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 = "../../ace-2a3cd908.js" > < / script >
< script src = "../../mode-rust-2c9d5c9a.js" > < / script >
< script src = "../../editor-16ca416c.js" > < / script >
< script src = "../../theme-dawn-4493f9c8.js" > < / script >
< script src = "../../theme-tomorrow_night-9dbe62a9.js" > < / script >
< script src = "../../elasticlunr-ef4e11c1.min.js" > < / script >
< script src = "../../mark-09e88c2c.min.js" > < / script >
< script src = "../../searcher-c2a407aa.js" > < / script >
< script src = "../../clipboard-1626706a.min.js" > < / script >
< script src = "../../highlight-abc7f01d.js" > < / script >
< script src = "../../book-a0b12cfe.js" > < / script >
<!-- Custom JS scripts -->
< script src = "../../assets/custom-690c9de5.js" > < / script >
< script src = "../../assets/bigPicture-be03f9c8.js" > < / script >
< / div >
< / body >
< / html >