1
0
wiki/Technology/ProgrammingLanguage/Python/进阶/并行和并发.html

506 lines
526 KiB
HTML
Raw Normal View History

2024-09-06 10:58:26 +08:00
<!DOCTYPE html>
<html lang="zh"><head><title>并行和并发</title><meta charset="utf-8"/><link rel="preconnect" href="https://fonts.googleapis.com"/><link rel="preconnect" href="https://fonts.gstatic.com"/><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM Plex Mono&amp;family=Noto Serif Simplified Chinese:wght@400;700&amp;family=Source Sans Pro:ital,wght@0,400;0,600;1,400;1,600&amp;display=swap"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta property="og:title" content="并行和并发"/><meta property="og:description" content="Python 并行和并发."/><meta property="og:image" content="https://wiki.7wate.com/static/og-image.png"/><meta property="og:width" content="1200"/><meta property="og:height" content="675"/><link rel="icon" href="../../../../static/icon.png"/><meta name="description" content="Python 并行和并发."/><meta name="generator" content="Quartz"/><link href="../../../../index.css" rel="stylesheet" type="text/css" spa-preserve/><link href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css" rel="stylesheet" type="text/css" spa-preserve/><script src="../../../../prescript.js" type="application/javascript" spa-preserve></script><script type="application/javascript" spa-preserve>const fetchData = fetch("../../../../static/contentIndex.json").then(data => data.json())</script></head><body data-slug="Technology/ProgrammingLanguage/Python/进阶/并行和并发"><div id="quartz-root" class="page"><div id="quartz-body"><div class="left sidebar"><h2 class="page-title"><a href="../../../..">🪴 X·Eden</a></h2><div class="spacer mobile-only"></div><div class="search"><button class="search-button" id="search-button"><p>搜索</p><svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19.9 19.7"><title>Search</title><g class="search-path" fill="none"><path stroke-linecap="square" d="M18.5 18.3l-5.4-5.4"></path><circle cx="8" cy="8" r="7"></circle></g></svg></button><div id="search-container"><div id="search-space"><input autocomplete="off" id="search-bar" name="search" type="text" aria-label="搜索些什么" placeholder="搜索些什么"/><div id="search-layout" data-preview="true"></div></div></div></div><button class="darkmode" id="darkmode"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="dayIcon" x="0px" y="0px" viewBox="0 0 35 35" style="enable-background:new 0 0 35 35" xml:space="preserve" aria-label="暗色模式"><title>暗色模式</title><path d="M6,17.5C6,16.672,5.328,16,4.5,16h-3C0.672,16,0,16.672,0,17.5 S0.672,19,1.5,19h3C5.328,19,6,18.328,6,17.5z M7.5,26c-0.414,0-0.789,0.168-1.061,0.439l-2,2C4.168,28.711,4,29.086,4,29.5 C4,30.328,4.671,31,5.5,31c0.414,0,0.789-0.168,1.06-0.44l2-2C8.832,28.289,9,27.914,9,27.5C9,26.672,8.329,26,7.5,26z M17.5,6 C18.329,6,19,5.328,19,4.5v-3C19,0.672,18.329,0,17.5,0S16,0.672,16,1.5v3C16,5.328,16.671,6,17.5,6z M27.5,9 c0.414,0,0.789-0.168,1.06-0.439l2-2C30.832,6.289,31,5.914,31,5.5C31,4.672,30.329,4,29.5,4c-0.414,0-0.789,0.168-1.061,0.44 l-2,2C26.168,6.711,26,7.086,26,7.5C26,8.328,26.671,9,27.5,9z M6.439,8.561C6.711,8.832,7.086,9,7.5,9C8.328,9,9,8.328,9,7.5 c0-0.414-0.168-0.789-0.439-1.061l-2-2C6.289,4.168,5.914,4,5.5,4C4.672,4,4,4.672,4,5.5c0,0.414,0.168,0.789,0.439,1.06 L6.439,8.561z M33.5,16h-3c-0.828,0-1.5,0.672-1.5,1.5s0.672,1.5,1.5,1.5h3c0.828,0,1.5-0.672,1.5-1.5S34.328,16,33.5,16z M28.561,26.439C28.289,26.168,27.914,26,27.5,26c-0.828,0-1.5,0.672-1.5,1.5c0,0.414,0.168,0.789,0.439,1.06l2,2 C28.711,30.832,29.086,31,29.5,31c0.828,0,1.5-0.672,1.5-1.5c0-0.414-0.168-0.789-0.439-1.061L28.561,26.439z M17.5,29 c-0.829,0-1.5,0.672-1.5,1.5v3c0,0.828,0.671,1.5,1.5,1.5s1.5-0.672,1.5-1.5v-3C19,29.672,18.329,29,17.5,29z M17.5,7 C11.71,7,7,11.71,7,17.5S11.71,28,17.5,28S28,23.29,28,17.5S23.29,7,17.5,7z M17.5,25c-4.136,0-7.5-3.364-7.5-7.5 c0-4.136,3.364-7.5,7.5-7.5c4.136,0,7.5,3.364,7.5,7.5C25,21.636,21.636,25,17.5,25z"></path></svg><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="
<h3 id="并发与并行">并发与并行<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#并发与并行" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<pre><code class="mermaid">graph TD
concurrency[并发]
task1[任务1] --> run1[运行...]
task2[任务2] --> run2[运行...]
task3[任务3] --> run3[运行...]
concurrency --> task1
concurrency --> task2
concurrency --> task3
</code></pre>
<p><strong>并发Concurrency指的是多个任务在近似同一时间内启动和运行的能力。<strong>不同于并行,这些任务不一定在同一时间点真正地执行,但它们可能看起来似乎是同时进行的。这经常是</strong>通过任务切换或调度来实现的</strong>,使得每个任务都可以得到处理器的时间片,并轮流执行。</p>
<blockquote>
<p>例子:一个银行柜台,只有一位出纳员,但有多位客户在排队等待服务。出纳员可能会处理第一个客户的部分业务,然后转向第二个客户处理其业务,之后再返回第一个客户,以此类推。</p>
<p>尽管在任何特定时刻只有一个客户正在得到服务,但因为切换得足够快,所有的客户可能都觉得自己几乎是在同一时间得到服务的。这就是并发。</p>
</blockquote>
<pre><code class="mermaid">
graph TD
parallelism[并行]
cpu1[处理单元1] --> run1[运行任务1]
cpu2[处理单元2] --> run2[运行任务2]
cpu3[处理单元3] --> run3[运行任务3]
parallelism --> cpu1
parallelism --> cpu2
parallelism --> cpu3
</code></pre>
<p>**并行Parallelism指的是多个任务或多个处理单元在同一时刻真正地同时执行。**与并发不同,它不仅仅是任务准备同时运行或看似同时运行,而是真正地在同一时刻执行。这通常在具有多个处理器或多个核心的计算机系统中发生。</p>
<blockquote>
<p>例子:一个快餐店,里面有三个员工。当三位顾客同时走进店内并分别点餐时,如果每位员工分别为每位顾客制作餐点,而且三位员工都在同一时刻开始并同时完成任务,那么这就是并行。</p>
<p>每位员工和他们分别服务的顾客可以看作是一个处理单元和一个任务。</p>
</blockquote>
<h3 id="同步与异步">同步与异步<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#同步与异步" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<pre><code class="mermaid">graph TD
synchronous[同步]
op1[操作1] --> op2[操作2]
op2 --> op3[操作3]
synchronous --> op1
</code></pre>
<p>**同步Synchronous描述的是一个操作或任务需要等待另一个操作或任务完成之后才能开始或继续执行。**它通常涉及一种线性或顺序的流程,其中一个操作完全依赖于另一个操作的完成。</p>
<blockquote>
<p>例子:在超市结账时,如果只有一个收银员,那么顾客需要按照顺序来结账。第一个顾客必须完成结账并离开,第二个顾客才能开始结账,以此类推。</p>
<p>这里的每个结账过程都是同步的,因为每个顾客的结账必须在前一个顾客完成后才能开始。</p>
</blockquote>
<pre><code class="mermaid">graph LR
asynchronous[异步]
op1[操作1] --> callback1[回调1]
op2[操作2]
op3[操作3]
asynchronous --> op1
asynchronous --> op2
asynchronous --> op3
</code></pre>
<p>**异步Asynchronous描述的是一个操作开始后并不需要等待其完成可以继续执行其他操作。**一旦异步操作完成,通常通过回调、事件、通知或其他机制来获取结果或进一步处理。</p>
<blockquote>
<p>例子:你在一家咖啡店点了一杯咖啡。而不是站在柜台等待咖啡制作完成,你可以找个座位坐下,甚至看书或工作。当咖啡制作好,店员会叫你的名字或号码,此时你前去取杯。</p>
<p>在这个期间,你并没有闲置,而是进行了其他活动。</p>
</blockquote>
<h3 id="阻塞与非阻塞">阻塞与非阻塞<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#阻塞与非阻塞" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<pre><code class="mermaid">graph TD
blocking[阻塞]
op1[操作1] --> wait[等待资源...]
blocking --> op1
</code></pre>
<p>阻塞Blocking描述的是当一个操作或任务等待某个条件通常是某种资源满足时它会进入一个暂停或等待状态。在该条件被满足之前操作或任务不会继续执行。</p>
<blockquote>
<p>例子:你在电话上等待客服代表。在你等待的时候,你不能使用电话进行其他通话,也不能结束当前的通话,直到客服代表接听你的电话。</p>
<p>在这段时间里,你的电话线路被阻塞。</p>
</blockquote>
<pre><code class="mermaid">graph LR
nonBlocking[非阻塞]
op1[操作1] --> return[立即返回]
continueOp[继续其他操作]
nonBlocking --> op1
op1 --> continueOp
</code></pre>
<p>**非阻塞Non-blocking描述的是当一个操作或任务遇到必须等待的条件如等待某种资源它不会进入暂停或等待状态而是立即返回让程序可以继续执行其他操作。**当原始操作可以继续进行时,它会在适当的时间继续。</p>
<blockquote>
<p>例子:一个自助餐厅。即使前面的人在选择食物并花费很长时间,你也可以选择跳过他们,去取你想要的食物,而不必等待。</p>
<p>这种情况下,你的选择流程是非阻塞的</p>
</blockquote>
<h3 id="特性对比">特性对比<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#特性对比" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<div class="table-container"><table><thead><tr><th>特性</th><th>适用背景</th><th>优点</th><th>缺点</th><th>注意事项</th></tr></thead><tbody><tr><td>并发</td><td>多任务需在相近的时间内执行但不一定同时 - 单核或多核系统</td><td>资源高效利用、提高响应性</td><td>任务管理和调度可能复杂</td><td>需要避免任务间的资源争用</td></tr><tr><td>并行</td><td>同时执行多任务、多核或多处理器系统</td><td>性能大幅提升、任务真正同时执行</td><td>需要硬件支持、并行化设计可能复杂</td><td>要注意数据共享和并行任务之间的同步</td></tr><tr><td>同步</td><td>当一个任务需要另一个任务的结果时、线性流程</td><td>简单易理解、流程清晰</td><td>可能导致资源浪费和延迟</td><td>避免长时间的同步操作</td></tr><tr><td>异步</td><td>当任务之间无直接依赖关系、同时处理多个操作时</td><td>提高效率、无需等待</td><td>需要处理任务完成的回调或通知</td><td>要确保正确处理回调和错误</td></tr><tr><td>阻塞</td><td>当任务需要等待某资源或条件满足时</td><td>简单的编程模型、确保条件满足</td><td>导致程序或线程停滞、资源可能被浪费</td><td>尽量避免长时间的阻塞操作</td></tr><tr><td>非阻塞</td><td>当任务在等待某条件时仍需进行其他操作</td><td>响应迅速、资源高效利用</td><td>程序逻辑可能变得复杂</td><td>需要检查操作是否真的完成或资源是否真的可用</td></tr></tbody></table></div>
<h2 id="进程和线程">进程和线程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#进程和线程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<h3 id="进程">进程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#进程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<h4 id="进程是什么">进程是什么<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#进程是什么" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p><strong>进程是计算机中的程序关于某数据集的一次运行活动。<strong>它是</strong>系统资源分配的基本单位</strong>,并拥有独立的内存空间。进程具有自己的代码段、数据段和系统资源。</p>
<h4 id="为什么需要进程">为什么需要进程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#为什么需要进程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<ul>
<li>进程使操作系统可以<strong>多任务处理</strong>,同时执行多个程序。每个进程在其独立的地址空间中运行,互不干扰。</li>
<li>进程提供了应用<strong>程序执行的隔离环境</strong>,确保一个进程的故障不会影响到其他进程。</li>
<li>进程间的隔离也<strong>增强了系统的安全性</strong></li>
</ul>
<h4 id="进程间通信ipc队列管道">进程间通信IPC队列管道<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#进程间通信ipc队列管道" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<ul>
<li><strong>IPCInter-Process Communication</strong>:允许进程间相互通信和同步的技术。它包括信号、消息、共享内存等方法。</li>
<li><strong>队列</strong>是一个先进先出FIFO的数据结构可以用于进程间发送消息。</li>
<li><strong>管道</strong>:是一个双向通信的方法,允许一个进程的输出成为另一个进程的输入。管道通常用于父子进程间的通信。</li>
</ul>
<h3 id="线程">线程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#线程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<h4 id="线程是什么">线程是什么<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#线程是什么" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>线程是进程内部的执行单位,它是 <strong>CPU 调度和分派的基本单位。同一进程内的线程共享进程的资源</strong>,如内存、文件句柄等。但每个线程有其自己的运行栈和程序计数器。</p>
<h4 id="threading-模块"><code>threading</code> 模块<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#threading-模块" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>Python 的 <code>threading</code> 模块提供了低级线程 API使我们可以轻松创建和管理线程。以下是如何使用 <code>threading.Thread</code> 创建新线程的示例:</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> print_numbers</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> for</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> i </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">in</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> range</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">10</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(i)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">thread </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading.Thread(</span><span style="--shiki-light:#E36209;--shiki-dark:#FFAB70;">target</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">print_numbers)</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">thread.start()</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">thread.join()</span></span></code></pre></figure>
<h3 id="全局解释器锁gil">全局解释器锁GIL<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#全局解释器锁gil" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<h4 id="gil-是什么">GIL 是什么<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#gil-是什么" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>GIL 是 Python 解释器中的一个锁,它使得任何时候只有一个线程在执行。此锁仅存在于 CPython 解释器中。</p>
<blockquote>
<p>Python 官方社区计划在 3.12 以后版本逐步移除 GIL 锁。</p>
</blockquote>
<h4 id="gil-的存在原因">GIL 的存在原因<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#gil-的存在原因" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<ul>
<li>GIL 的主要目的是<strong>简化 CPythonPython 的标准解释器)的实现</strong>。由于多线程并发访问数据可能会导致数据损坏或不一致的情况GIL 可以防止这种情况的发生。</li>
<li>CPython 的内存管理不是线程安全的GIL 可以保证同时只有一个线程执行 Python 字节码,从而避免并发访问的问题。</li>
</ul>
<h4 id="gil-对多线程程序的影响">GIL 对多线程程序的影响<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#gil-对多线程程序的影响" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<ul>
<li>由于 GIL 的存在,<strong>多线程的 Python 程序不能充分利用多核心 CPU 的优势</strong>因为任何时候都只有一个线程在执行。这意味着在计算密集型任务上Python 的多线程并不总是有效的。</li>
<li>对于 I/O 密集型任务,多线程仍然是有效的,因为线程在等待 I/O 操作完成时可以释放 GIL这允许其他线程执行。</li>
<li>要真正充分利用多核心Python 开发者通常会使用进程级的并发(如 <code>multiprocessing</code> 模块)或使用其他没有 GIL 限制的 Python 实现,例如 Jython 或 IronPython。</li>
</ul>
<h2 id="python-并发库">Python 并发库<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#python-并发库" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<p>并发是一种技术可以使多个任务似乎在同一时间执行。Python 提供了多种方式来实现并发,以下是其中的一些主要方式。</p>
<h3 id="multiprocessing多进程"><code>multiprocessing</code>:多进程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#multiprocessing多进程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>Python 由于 GIL全局解释器锁的存在在多线程时并不能充分利用多核 CPU。为了避免 GIL 的限制,可以使用 <code>multiprocessing</code> 模块创建多个进程。</p>
<ul>
<li>
<p><strong>优点</strong>:可以充分利用多核 CPU、进程间内存是隔离的增加了安全性。</p>
</li>
<li>
<p>**缺点:**进程启动和通信相对较慢。</p>
</li>
</ul>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">from</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> multiprocessing </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> Process</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> print_hello</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(name):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">f</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">&quot;Hello, </span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">{</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">name</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">}</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">!&quot;</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出Hello, world!</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">p </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> Process(</span><span style="--shiki-light:#E36209;--shiki-dark:#FFAB70;">target</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">print_hello, </span><span style="--shiki-light:#E36209;--shiki-dark:#FFAB70;">args</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'world'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">,))</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">p.start()</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">p.join()</span></span></code></pre></figure>
<h3 id="concurrentfutures线程池与进程池"><code>concurrent.futures</code>:线程池与进程池<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#concurrentfutures线程池与进程池" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p><code>concurrent.futures</code> 提供了高层次的异步执行接口,支持线程池和进程池。</p>
<h4 id="线程池">线程池<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#线程池" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>线程比进程轻量,创建和切换成本较低,但受到 GIL 的限制。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">from</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> concurrent.futures </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> ThreadPoolExecutor</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 使用线程池</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> ThreadPoolExecutor(</span><span style="--shiki-light:#E36209;--shiki-dark:#FFAB70;">max_workers</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">4</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">as</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> executor:</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> results </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> list</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(executor.map(print_hello, [</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'world'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">, </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'python'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">, </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'asyncio'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">]))</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 输出(注意:线程执行的顺序可能是不确定的,以下只是一个可能的输出):</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # Hello, world!</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # Hello, python!</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # Hello, asyncio!</span></span></code></pre></figure>
<h4 id="进程池">进程池<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#进程池" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">from</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> concurrent.futures </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> ProcessPoolExecutor</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 使用进程池</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> ProcessPoolExecutor(</span><span style="--shiki-light:#E36209;--shiki-dark:#FFAB70;">max_workers</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">4</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">as</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> executor:</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> results </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> list</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(executor.map(print_hello, [</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'world'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">, </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'python'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">, </span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'asyncio'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">]))</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 输出(进程的执行顺序可能是不确定的,以下只是一个可能的输出):</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # Hello, world!</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # Hello, python!</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # Hello, asyncio!</span></span></code></pre></figure>
<h3 id="asyncio异步协程"><code>asyncio</code>:异步协程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#asyncio异步协程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p><code>asyncio</code> 是 Python 的异步编程框架,它使用事件循环驱动的协程来实现并发。</p>
<h4 id="事件循环">事件循环<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#事件循环" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>事件循环是异步编程的核心,用于调度和执行任务,确保异步任务的非阻塞执行。通过使用 <code>asyncio.get_event_loop()</code> 获取当前事件循环。</p>
<h4 id="协程">协程<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#协程" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>协程是 <code>asyncio</code> 的核心部分。使用 <code>async def</code> 定义协程,使用 <code>await</code> 在协程中等待另一个协程完成。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> asyncio</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> main</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'Hello'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出Hello</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> await</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> asyncio.sleep(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">1</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'World'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出World</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">asyncio.run(main())</span></span></code></pre></figure>
<h3 id="高级异步特性">高级异步特性<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#高级异步特性" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<h4 id="异步生成器">异步生成器<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#异步生成器" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>可以在一个异步函数中产生多个值。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> asyncio</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> async_gen</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> for</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> i </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">in</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> range</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">3</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">):</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> await</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> asyncio.sleep(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">1</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> yield</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> i</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> main_gen</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> for</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> value </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">in</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> async_gen():</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(value) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出0 1 2</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">asyncio.run(main())</span></span>
<span data-line> </span></code></pre></figure>
<h4 id="异步上下文管理器">异步上下文管理器<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#异步上下文管理器" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>允许使用 <code>async with</code> 语句进行异步资源管理。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">class</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> AsyncContextManager</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> __aenter__</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">&quot;Entered the async context.&quot;</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出Entered the async context.</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> return</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> self</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> </span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> __aexit__</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self, exc_type, exc, tb):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">&quot;Exited the async context.&quot;</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出Exited the async context.</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> main_context</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> async</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> AsyncContextManager() </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">as</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> acm:</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">&quot;Inside the async context.&quot;</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">) </span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 输出Inside the async context.</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">asyncio.run(main_context())</span></span></code></pre></figure>
<p>Python 的并发库为开发者提供了多种选择,选择哪种方式取决于具体的应用需求和场景。不管选择哪种方式,重要的是理解其背后的工作原理和限制,这样可以更好地实现并发,并提高应用的性能。</p>
<h2 id="其他异步框架和库">其他异步框架和库<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#其他异步框架和库" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<h3 id="tornado">Tornado<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#tornado" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>Tornado 是一个 Python Web 服务器软件的开放源码版本。由于其非阻塞 I/O 设计它能够处理大量的长连接非常适用于长轮询、WebSockets 等网络协议。与传统的多线程和多进程服务器相比Tornado 使用单线程事件循环,可以高效地管理数千甚至数百万的并发连接。</p>
<h3 id="twisted">Twisted<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#twisted" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>Twisted 是一个事件驱动的网络引擎,用于构建各种网络应用。除了支持常见的网络协议如 HTTP、SMTP、POP3、FTP 等Twisted 还提供了其它功能如身份验证、SSL 和其他安全特性。Twisted 的设计理念是为开发者提供最大的灵活性,允许他们使用自己喜欢的工具和库。</p>
<h3 id="quart">Quart<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#quart" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>Quart 是一个基于 Python 的 ASGI Web 微框架。尽管它的 API 与 Flask 极为相似,但由于集成了 asyncio 的异步功能Quart 可以提供更高的响应速度。使用 Quart开发者可以无缝地将 Flask 代码迁移到一个异步环境中,从而充分利用现代硬件的并发性。</p>
<h2 id="锁信号量和同步原语">锁、信号量和同步原语<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#锁信号量和同步原语" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<h3 id="互斥锁-mutex">互斥锁 (Mutex)<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#互斥锁-mutex" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>**互斥锁确保特定资源或代码段在同一时间只能被一个线程访问。**例如,如果两个线程尝试同时更新一个共享的数据结构,没有适当的同步可能会导致数据损坏。互斥锁就是这样一个保护机制,确保资源的一致性和完整性。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 创建一个互斥锁</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">mutex </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading.Lock()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> update_data</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 获取锁</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> mutex.acquire()</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> </span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> try</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 更新共享资源</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> pass</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> finally</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 释放锁</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> mutex.release()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 启动多个线程来调用update_data</span></span></code></pre></figure>
<h3 id="读写锁">读写锁<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#读写锁" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>读写锁是一种特殊的锁,针对读者 - 作者问题而设计。当资源经常被读取但很少被修改时,读写锁是很有用的。在这种情况下,多个读线程可以并发访问资源,但写线程会阻塞所有其他线程,确保在写操作期间资源的完整性。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">from</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> rwlock </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> RWLock</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">rwlock </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> RWLock()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> read_data</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> rwlock.r_lock():</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 读取数据</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> pass</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> write_data</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> rwlock.w_lock():</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 修改数据</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> pass</span></span></code></pre></figure>
<h3 id="信号量-semaphore">信号量 (Semaphore)<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#信号量-semaphore" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>与互斥锁不同,信号量允许多个线程并发访问资源,但是数量是有限的。例如,如果你有一个包含 5 个数据库连接的连接池,你可以使用一个计数为 5 的信号量来确保任何时候最多只有 5 个线程使用这些连接。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 创建一个信号量最多允许5个线程同时访问</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">semaphore </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading.Semaphore(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">5</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> access_resource</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 获取信号量</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> semaphore.acquire()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> try</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 访问资源</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> pass</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> finally</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 释放信号量</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> semaphore.release()</span></span></code></pre></figure>
<h3 id="条件变量">条件变量<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#条件变量" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>条件变量是用于线程之间的同步,特别是当线程需要等待特定条件成立时。例如,一个线程可能会等待一个队列非空才开始处理。使用条件变量,这个线程可以在队列为空时进入休眠,并在其他线程向队列添加项时被唤醒。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">condition </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading.Condition()</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">queue </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> []</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> produce_item</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> condition:</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 生产一个项目并添加到队列</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> queue.append(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">&quot;item&quot;</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 唤醒等待队列非空的线程</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> condition.notify()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> consume_item</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> with</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> condition:</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> while</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> not</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> queue:</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # 如果队列为空,则等待</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> condition.wait()</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 从队列中消费一个项目</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> item </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> queue.pop()</span></span></code></pre></figure>
<h2 id="设计模式与最佳实践">设计模式与最佳实践<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#设计模式与最佳实践" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<h3 id="生产者---消费者模式">生产者 - 消费者模式<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#生产者---消费者模式" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>生产者 - 消费者模式是一个并发模式,其中一个或多个生产者线程创建项目,而一个或多个消费者线程处理这些项目。这种模式可以有效地分离数据生产和数据处理,通常使用队列来传输数据。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> threading</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> queue</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">q </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> queue.Queue()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> producer</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> while</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> True</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> item </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> produce_item()</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> q.put(item)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> consumer</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> while</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> True</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> item </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> q.get()</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> process_item(item)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> produce_item</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 生产数据</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> return</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;"> &quot;item&quot;</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> process_item</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(item):</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 处理数据</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> pass</span></span></code></pre></figure>
<h3 id="发布者---订阅者模式">发布者 - 订阅者模式<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#发布者---订阅者模式" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<p>发布者 - 订阅者模式是一种通知模式,其中发布者发送通知,而订阅者(可以有多个)接收通知。这种模式适用于需要广播信息的场景。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">class</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> Publisher</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> __init__</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> self</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">.subscribers </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> set</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> register</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self, who):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> self</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">.subscribers.add(who)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> unregister</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self, who):</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> self</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">.subscribers.discard(who)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> dispatch</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self, message):</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> for</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> subscriber </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">in</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> self</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">.subscribers:</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> subscriber.update(message)</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">class</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> Subscriber</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">:</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> update</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(self, message):</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 处理消息</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(message)</span></span></code></pre></figure>
<h3 id="避免死锁资源竞争线程安全的设计">避免死锁、资源竞争、线程安全的设计<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#避免死锁资源竞争线程安全的设计" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<ul>
<li><strong>避免死锁</strong>:确保线程按照一致的顺序请求资源,使用锁的超时功能,或使用死锁检测工具。</li>
<li><strong>资源竞争</strong>:使用锁、信号量等同步原语确保对共享资源的有序访问。</li>
<li><strong>线程安全的设计</strong>:避免修改共享数据,或确保使用适当的同步机制来保护数据。考虑使用不可变数据结构和线程局部存储。</li>
</ul>
<h2 id="实际应用与性能分析">实际应用与性能分析<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#实际应用与性能分析" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h2>
<h3 id="选择适当的并发或并行工具">选择适当的并发或并行工具<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#选择适当的并发或并行工具" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<ul>
<li><strong>任务性质</strong>I/O 密集型任务可以从多线程中受益,而 CPU 密集型任务可能更适合多进程或异步编程。</li>
<li><strong>共享数据</strong>:如果需要大量共享数据,则线程可能是一个好选择;否则,多进程可能更简单。</li>
</ul>
<h3 id="性能分析工具">性能分析工具<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#性能分析工具" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<h4 id="cprofile"><code>cProfile</code><a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#cprofile" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p><code>cProfile</code> 是 Python 的一个内置性能分析工具。它测量函数调用的频率和执行时间,对于查找瓶颈和代码优化尤为有用。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> cProfile</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> my_function</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"> # </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">TODO</span><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;">: 一些代码</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> pass</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">cProfile.run(</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">'my_function()'</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span></code></pre></figure>
<h4 id="memory_profiler"><code>memory_profiler</code><a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#memory_profiler" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p><code>memory_profiler</code> 是一个用于监控 Python 程序内存使用的工具,它可以为你提供关于对象的内存消耗等信息。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">from</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> memory_profiler </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> profile</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;">@profile</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> memory_test_func</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> a </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> [i </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">for</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> i </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">in</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> range</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">100000</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)]</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> return</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> a</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">memory_test_func()</span></span></code></pre></figure>
<h4 id="timeit"><code>timeit</code><a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#timeit" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p><code>timeit</code> 是一个专门用于<strong>测量小代码片段执行时间</strong>的工具。它的优势在于,它会多次运行指定的代码,以获取更精确的平均运行时间。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> timeit</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">def</span><span style="--shiki-light:#6F42C1;--shiki-dark:#B392F0;"> code_to_test</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">():</span></span>
<span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;"> return</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> sum</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">range</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">10000</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">))</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 该方法会运行 `code_to_test` 函数 1000 次,并返回总运行时间</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">elapsed_time </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> timeit.timeit(code_to_test, </span><span style="--shiki-light:#E36209;--shiki-dark:#FFAB70;">number</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">1000</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(elapsed_time)</span></span>
<span data-line> </span></code></pre></figure>
<h4 id="timeprocess_time"><code>time.process_time</code><a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#timeprocess_time" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p>这个函数返回<strong>当前进程运行的 CPU 时间,而不是实际经过的时间</strong>,它可以帮助我们忽略其他进程或线程对测量结果的影响。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="Python" data-theme="github-light github-dark"><code data-language="Python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span>import time</span></span>
<span data-line> </span>
<span data-line><span>start = time.process_time()</span></span>
<span data-line> </span>
<span data-line><span># 要测量的代码</span></span>
<span data-line><span>result = sum(range(1000000))</span></span>
<span data-line> </span>
<span data-line><span>end = time.process_time()</span></span>
<span data-line><span>print(f&quot;Time taken: {end - start} seconds&quot;)</span></span></code></pre></figure>
<h4 id="timeperf_counter"><code>time.perf_counter</code><a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#timeperf_counter" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h4>
<p><code>time.perf_counter</code> 是一个高分辨率的计时器,适合对代码段进行基准测试,并且还会计算系统的休眠时间。</p>
<figure data-rehype-pretty-code-figure><pre tabindex="0" data-language="python" data-theme="github-light github-dark"><code data-language="python" data-theme="github-light github-dark" style="display:grid;"><span data-line><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">import</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> time</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">start </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> time.perf_counter()</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#6A737D;--shiki-dark:#6A737D;"># 要测量的代码</span></span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">result </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;"> sum</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">range</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">1000000</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">))</span></span>
<span data-line> </span>
<span data-line><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">end </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">=</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> time.perf_counter()</span></span>
<span data-line><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">print</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">(</span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">f</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;">&quot;Time taken: </span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">{</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">end </span><span style="--shiki-light:#D73A49;--shiki-dark:#F97583;">-</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;"> start</span><span style="--shiki-light:#005CC5;--shiki-dark:#79B8FF;">}</span><span style="--shiki-light:#032F62;--shiki-dark:#9ECBFF;"> seconds&quot;</span><span style="--shiki-light:#24292E;--shiki-dark:#E1E4E8;">)</span></span></code></pre></figure>
<h3 id="优化策略">优化策略<a role="anchor" aria-hidden="true" tabindex="-1" data-no-popover="true" href="#优化策略" class="internal"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg></a></h3>
<ul>
<li><strong>减少锁的使用</strong>:频繁使用锁可能导致线程等待,降低整体性能。尝试减少锁的持有时间或使用更细粒度的锁,以减少资源争用。</li>
<li><strong>使用线程池和连接池</strong>:通过预先创建和复用线程或数据库连接,可以避免频繁地创建和销毁资源,这可以显著提高性能。</li>
<li><strong>优化数据结构和算法</strong>:选择正确的数据结构和算法可以极大地提高代码的运行效率。定期审查代码,确保它是最优的。</li>
<li><strong>利用缓存</strong>:将常用的计算结果或查询结果缓存起来,可以避免重复的、消耗性能的操作。</li>
<li><strong>延迟加载</strong>:只有在真正需要时再加载数据,这样可以避免不必要的计算和资源使用。</li>
</ul></article><hr/><div class="page-footer"></div></div><div class="right sidebar"><div class="graph"><h3>关系图谱</h3><div class="graph-outer"><div id="graph-container" data-cfg="{&quot;drag&quot;:true,&quot;zoom&quot;:true,&quot;depth&quot;:1,&quot;scale&quot;:1.1,&quot;repelForce&quot;:0.5,&quot;centerForce&quot;:0.3,&quot;linkDistance&quot;:30,&quot;fontSize&quot;:0.6,&quot;opacityScale&quot;:1,&quot;showTags&quot;:true,&quot;removeTags&quot;:[],&quot;focusOnHover&quot;:false}"></div><button id="global-graph-icon" aria-label="Global Graph"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 55 55" fill="currentColor" xml:space="preserve"><path d="M49,0c-3.309,0-6,2.691-6,6c0,1.035,0.263,2.009,0.726,2.86l-9.829,9.829C32.542,17.634,30.846,17,29,17
s-3.542,0.634-4.898,1.688l-7.669-7.669C16.785,10.424,17,9.74,17,9c0-2.206-1.794-4-4-4S9,6.794,9,9s1.794,4,4,4
c0.74,0,1.424-0.215,2.019-0.567l7.669,7.669C21.634,21.458,21,23.154,21,25s0.634,3.542,1.688,4.897L10.024,42.562
C8.958,41.595,7.549,41,6,41c-3.309,0-6,2.691-6,6s2.691,6,6,6s6-2.691,6-6c0-1.035-0.263-2.009-0.726-2.86l12.829-12.829
c1.106,0.86,2.44,1.436,3.898,1.619v10.16c-2.833,0.478-5,2.942-5,5.91c0,3.309,2.691,6,6,6s6-2.691,6-6c0-2.967-2.167-5.431-5-5.91
v-10.16c1.458-0.183,2.792-0.759,3.898-1.619l7.669,7.669C41.215,39.576,41,40.26,41,41c0,2.206,1.794,4,4,4s4-1.794,4-4
s-1.794-4-4-4c-0.74,0-1.424,0.215-2.019,0.567l-7.669-7.669C36.366,28.542,37,26.846,37,25s-0.634-3.542-1.688-4.897l9.665-9.665
C46.042,11.405,47.451,12,49,12c3.309,0,6-2.691,6-6S52.309,0,49,0z M11,9c0-1.103,0.897-2,2-2s2,0.897,2,2s-0.897,2-2,2
S11,10.103,11,9z M6,51c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S8.206,51,6,51z M33,49c0,2.206-1.794,4-4,4s-4-1.794-4-4
s1.794-4,4-4S33,46.794,33,49z M29,31c-3.309,0-6-2.691-6-6s2.691-6,6-6s6,2.691,6,6S32.309,31,29,31z M47,41c0,1.103-0.897,2-2,2
s-2-0.897-2-2s0.897-2,2-2S47,39.897,47,41z M49,10c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S51.206,10,49,10z"></path></svg></button></div><div id="global-graph-outer"><div id="global-graph-container" data-cfg="{&quot;drag&quot;:true,&quot;zoom&quot;:true,&quot;depth&quot;:-1,&quot;scale&quot;:0.9,&quot;repelForce&quot;:0.5,&quot;centerForce&quot;:0.3,&quot;linkDistance&quot;:30,&quot;fontSize&quot;:0.6,&quot;opacityScale&quot;:1,&quot;showTags&quot;:true,&quot;removeTags&quot;:[],&quot;focusOnHover&quot;:true}"></div></div></div><div class="toc desktop-only"><button type="button" id="toc" class aria-controls="toc-content" aria-expanded="true"><h3>目录</h3><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="fold"><polyline points="6 9 12 15 18 9"></polyline></svg></button><div id="toc-content" class><ul class="overflow"><li class="depth-0"><a href="#基础概念" data-for="基础概念">基础概念</a></li><li class="depth-1"><a href="#并发与并行" data-for="并发与并行">并发与并行</a></li><li class="depth-1"><a href="#同步与异步" data-for="同步与异步">同步与异步</a></li><li class="depth-1"><a href="#阻塞与非阻塞" data-for="阻塞与非阻塞">阻塞与非阻塞</a></li><li class="depth-1"><a href="#特性对比" data-for="特性对比">特性对比</a></li><li class="depth-0"><a href="#进程和线程" data-for="进程和线程">进程和线程</a></li><li class="depth-1"><a href="#进程" data-for="进程">进程</a></li><li class="depth-1"><a href="#线程" data-for="线程">线程</a></li><li class="depth-1"><a href="#全局解释器锁gil" data-for="全局解释器锁gil">全局解释器锁GIL</a></li><li class="depth-0"><a href="#python-并发库" data-for="python-并发库">Python 并发库</a></li><li class="depth-1"><a href="#multiprocessing多进程" data-for="multiprocessing多进程">multiprocessing多进程</a></li><li class="depth-1"><a href="#concurrentfutures线程池与进程池" data-for="concurrentfutures线程池与进程池">concurrent.futures线程池与进程池</a></li><li class="depth-1"><a href="#asyncio异步协程" data-for="asyncio异步协程">asyncio异步协程</a></li><li class="depth-1"><a href="#高级异步特性" data-for="高级异步特性">高级异步特性</a></li><li class="depth-0"><a href="#其他异步框架和库" data-for="其他异步框架和库">其他异步框架和库</a></li><li class="depth-1"><a href="#tornado" data-for="tornado">Tornado</a></li><li class="depth-1"><a href="#twisted" data-for="twisted">Twisted</a></li><li class="depth-1"><a href="#quart" data-for="quart">Quart</a></li><li class="depth-0"><a href="#锁信号量和同步原语" data-for="锁信号量和同步原语">锁、信号量和同步原语</a></li><li class="depth-1"><a href="#互斥锁-mutex" data-for="互斥锁-mutex">互斥锁 (Mutex)</a></li><li class="depth-1"><a href="#读写锁" data-for="读写锁">读写锁</a></li><li class="depth-1"><a href="#信号量-semaphore" data-for="信号量-semaphore">信号量 (Semaphore)</a></li><li class="depth-1"><a href="#条件变量" data-for="条件变量">条件变量</a></li><li class="depth-0"><a href="#设计模式与最佳实践" data-for="设计模式与最佳实践">设计模式与最佳实践</a></li><li class="depth-1"><a href="#生产者---消费者模式" data-for="生产者---消费者模式">生产者 - 消费者模式</a></li><li class="depth-1"><a href="#发布者---订阅者模式" data-for="发布者---订阅者模式">发布者 - 订阅者模式</a></li><li class="depth-1"><a href="#避免死锁资源竞争线程安全的设计" data-for="避免死锁资源竞争线程安全的设计">避免死锁、资源竞争、线程安全的设计</a></li><li class="depth-0"><a href="#实际应用与性能分析" data-for="实际应用与性能分析">实际应用与性能分析</a></li><li class="depth-1"><a href="#选择适当的并发或<E58F91>
</script><script type="module">
let mermaidImport = undefined
document.addEventListener('nav', async () => {
if (document.querySelector("code.mermaid")) {
mermaidImport ||= await import('https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.7.0/mermaid.esm.min.mjs')
const mermaid = mermaidImport.default
const darkMode = document.documentElement.getAttribute('saved-theme') === 'dark'
mermaid.initialize({
startOnLoad: false,
securityLevel: 'loose',
theme: darkMode ? 'dark' : 'default'
})
await mermaid.run({
querySelector: '.mermaid'
})
}
});
</script><script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/contrib/copy-tex.min.js" type="application/javascript"></script><script src="../../../../postscript.js" type="module"></script></html>