“Python/docs/3.9/library/concurrent.futures”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/concurrent.futures
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:concurrent.futures — 启动并行任务 — Python 文档}}
 
<div id="module-concurrent.futures" class="section">
 
<div id="module-concurrent.futures" class="section">
  
 
<span id="concurrent-futures-launching-parallel-tasks"></span>
 
<span id="concurrent-futures-launching-parallel-tasks"></span>
= [[#module-concurrent.futures|<code>concurrent.futures</code>]] --- Launching parallel tasks =
+
= concurrent.futures — 启动并行任务 =
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.2 新版功能.</span>
+
<span class="versionmodified added">3.2 版中的新功能。</span>
  
  
 
</div>
 
</div>
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/concurrent/futures/thread.py Lib/concurrent/futures/thread.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/concurrent/futures/thread.py`</span>]]
and [https://github.com/python/cpython/tree/3.9/Lib/concurrent/futures/process.py Lib/concurrent/futures/process.py]
+
and [[#id3|<span id="id4" class="problematic">:source:`Lib/concurrent/futures/process.py`</span>]]
  
The [[#module-concurrent.futures|<code>concurrent.futures</code>]] module provides a high-level interface for
 
asynchronously executing callables.
 
  
The asynchronous execution can be performed with threads, using
+
-----
[[#concurrent.futures.ThreadPoolExecutor|<code>ThreadPoolExecutor</code>]], or separate processes, using
+
 
[[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]]. Both implement the same interface, which is
+
[[#module-concurrent.futures|concurrent.futures]] 模块为异步执行可调用对象提供了一个高级接口。
defined by the abstract [[#concurrent.futures.Executor|<code>Executor</code>]] class.
+
 
 +
异步执行可以使用线程执行,使用 [[#concurrent.futures.ThreadPoolExecutor|ThreadPoolExecutor]],或单独的进程,使用 [[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]]。 两者都实现了相同的接口,该接口由抽象的 [[#concurrent.futures.Executor|Executor]] 类定义。
  
 
<div id="executor-objects" class="section">
 
<div id="executor-objects" class="section">
  
== Executor Objects ==
+
== 执行器对象 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>concurrent.futures.</code><code>Executor</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">Executor</span></span></dt>
<dd><p>An abstract class that provides methods to execute calls asynchronously. It
+
<dd><p>一个抽象类,提供异步执行调用的方法。 它不应直接使用,而应通过其具体的子类使用。</p>
should not be used directly, but through its concrete subclasses.</p>
 
 
<blockquote><div>
 
<blockquote><div>
  
 
<dl>
 
<dl>
<dt><code>submit</code><span class="sig-paren">(</span>''<span class="n">fn</span>'', ''<span class="o">/</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="o">**</span><span class="n">kwargs</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">submit</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fn</span></span>'', ''<span class="o"><span class="pre">/</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Schedules the callable, ''fn'', to be executed as <code>fn(*args **kwargs)</code>
+
<dd><p>安排可调用对象 ''fn'' <code>fn(*args **kwargs)</code> 的形式执行,并返回一个表示可调用对象执行的 [[#concurrent.futures.Future|Future]] 对象。</p>
and returns a [[#concurrent.futures.Future|<code>Future</code>]] object representing the execution of the
 
callable.</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>with ThreadPoolExecutor(max_workers=1) as executor:
+
<syntaxhighlight lang="python3">with ThreadPoolExecutor(max_workers=1) as executor:
 
     future = executor.submit(pow, 323, 1235)
 
     future = executor.submit(pow, 323, 1235)
     print(future.result())</pre>
+
     print(future.result())</syntaxhighlight>
  
 
</div>
 
</div>
第49行: 第46行:
  
 
<dl>
 
<dl>
<dt><code>map</code><span class="sig-paren">(</span>''<span class="n">func</span>'', ''<span class="o">*</span><span class="n">iterables</span>'', ''<span class="n">timeout</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">chunksize</span><span class="o">=</span><span class="default_value">1</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">map</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">func</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">iterables</span></span>'', ''<span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">chunksize</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Similar to [[../functions#map|<code>map(func, *iterables)</code>]] except:</p>
+
<dd><p>类似于 [[../functions#map|map(func, *iterables)]] 除了:</p>
 
<ul>
 
<ul>
<li><p>the ''iterables'' are collected immediately rather than lazily;</p></li>
+
<li><p>''iterables'' 立即收集而不是懒惰;</p></li>
<li><p>''func'' is executed asynchronously and several calls to
+
<li><p>''func'' 是异步执行的,并且可以同时调用多个 ''func''</p></li></ul>
''func'' may be made concurrently.</p></li></ul>
 
  
<p>The returned iterator raises a [[#concurrent.futures.TimeoutError|<code>concurrent.futures.TimeoutError</code>]]
+
<p>如果调用了 [[../stdtypes#iterator|__next__()]] 并且在 ''timeout'' 秒后结果不可用,则返回的迭代器会引发 [[#concurrent.futures.TimeoutError|concurrent.futures.TimeoutError]] X193X]Executor.map()''timeout'' 可以是 int 或 float。 如果未指定 ''timeout'' <code>None</code>,则等待时间没有限制。</p>
if [[../stdtypes#iterator|<code>__next__()</code>]] is called and the result isn't available
+
<p>如果 ''func'' 调用引发异常,则在从迭代器检索其值时将引发该异常。</p>
after ''timeout'' seconds from the original call to [[#concurrent.futures.Executor.map|<code>Executor.map()</code>]].
+
<p>当使用 [[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]] 时,这个方法将 ''iterables'' 分成许多块,作为单独的任务提交到池中。 这些块的(近似)大小可以通过将 ''chunksize'' 设置为正整数来指定。 对于非常长的可迭代对象,与默认大小 1 相比,使用较大的 ''chunksize'' 值可以显着提高性能。 使用 [[#concurrent.futures.ThreadPoolExecutor|ThreadPoolExecutor]]''chunksize'' 无效。</p>
''timeout'' can be an int or a float. If ''timeout'' is not specified or
 
<code>None</code>, there is no limit to the wait time.</p>
 
<p>If a ''func'' call raises an exception, then that exception will be
 
raised when its value is retrieved from the iterator.</p>
 
<p>When using [[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]], this method chops ''iterables''
 
into a number of chunks which it submits to the pool as separate
 
tasks. The (approximate) size of these chunks can be specified by
 
setting ''chunksize'' to a positive integer. For very long iterables,
 
using a large value for ''chunksize'' can significantly improve
 
performance compared to the default size of 1. With
 
[[#concurrent.futures.ThreadPoolExecutor|<code>ThreadPoolExecutor</code>]], ''chunksize'' has no effect.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>Added the ''chunksize'' argument.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> 添加 ''chunksize'' 参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>shutdown</code><span class="sig-paren">(</span>''wait=True'', ''\*'', ''cancel_futures=False''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">shutdown</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">wait</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">cancel_futures</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Signal the executor that it should free any resources that it is using
+
<dd><p>当当前挂起的期货完成执行时,通知执行器它应该释放它正在使用的任何资源。 关闭后调用 [[#concurrent.futures.Executor.submit|Executor.submit()]] [[#concurrent.futures.Executor.map|Executor.map()]] 将引发 [[../exceptions#RuntimeError|RuntimeError]]</p>
when the currently pending futures are done executing. Calls to
+
<p>如果 ''wait'' <code>True</code> 则此方法将不会返回,直到所有挂起的期货都执行完毕并且与执行程序关联的资源已被释放。 如果 ''wait'' <code>False</code> 则此方法将立即返回,并且当所有挂起的期货执行完毕后,与执行器关联的资源将被释放。 无论 ''wait'' 的值如何,在所有挂起的期货执行完毕之前,整个 Python 程序都不会退出。</p>
[[#concurrent.futures.Executor.submit|<code>Executor.submit()</code>]] and [[#concurrent.futures.Executor.map|<code>Executor.map()</code>]] made after shutdown will
+
<p>如果 ''cancel_futures'' <code>True</code>,则此方法将取消所有执行者尚未开始运行的挂起期货。 无论 ''cancel_futures'' 的值如何,任何已完成或正在运行的期货都不会被取消。</p>
raise [[../exceptions#RuntimeError|<code>RuntimeError</code>]].</p>
+
<p>如果 ''cancel_futures'' ''wait'' 都是 <code>True</code>,则执行器已开始运行的所有期货将在此方法返回之前完成。 剩余的期货被取消。</p>
<p>If ''wait'' is <code>True</code> then this method will not return until all the
+
<p>如果您使用 [[../../reference/compound_stmts#with|with]] 语句,您可以避免显式调用此方法,这将关闭 [[#concurrent.futures.Executor|Executor]](等待好像 [[#concurrent.futures.Executor.shutdown|Executor.shutdown()]] 被调用''wait'' 设置为 <code>True</code>):</p>
pending futures are done executing and the resources associated with the
 
executor have been freed. If ''wait'' is <code>False</code> then this method will
 
return immediately and the resources associated with the executor will be
 
freed when all pending futures are done executing. Regardless of the
 
value of ''wait'', the entire Python program will not exit until all
 
pending futures are done executing.</p>
 
<p>If ''cancel_futures'' is <code>True</code>, this method will cancel all pending
 
futures that the executor has not started running. Any futures that
 
are completed or running won't be cancelled, regardless of the value
 
of ''cancel_futures''.</p>
 
<p>If both ''cancel_futures'' and ''wait'' are <code>True</code>, all futures that the
 
executor has started running will be completed prior to this method
 
returning. The remaining futures are cancelled.</p>
 
<p>You can avoid having to call this method explicitly if you use the
 
[[../../reference/compound_stmts#with|<code>with</code>]] statement, which will shutdown the [[#concurrent.futures.Executor|<code>Executor</code>]]
 
(waiting as if [[#concurrent.futures.Executor.shutdown|<code>Executor.shutdown()</code>]] were called with ''wait'' set to
 
<code>True</code>):</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import shutil
+
<syntaxhighlight lang="python3">import shutil
 
with ThreadPoolExecutor(max_workers=4) as e:
 
with ThreadPoolExecutor(max_workers=4) as e:
 
     e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
 
     e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
 
     e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
 
     e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
 
     e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
 
     e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
     e.submit(shutil.copy, 'src4.txt', 'dest4.txt')</pre>
+
     e.submit(shutil.copy, 'src4.txt', 'dest4.txt')</syntaxhighlight>
  
 
</div>
 
</div>
第116行: 第84行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>Added ''cancel_futures''.</p>
+
<p><span class="versionmodified changed"> 3.9 版变更: </span> 添加 ''cancel_futures''</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第127行: 第95行:
 
<div id="threadpoolexecutor" class="section">
 
<div id="threadpoolexecutor" class="section">
  
== ThreadPoolExecutor ==
+
== 线程池执行器 ==
  
[[#concurrent.futures.ThreadPoolExecutor|<code>ThreadPoolExecutor</code>]] is an [[#concurrent.futures.Executor|<code>Executor</code>]] subclass that uses a pool of
+
[[#concurrent.futures.ThreadPoolExecutor|ThreadPoolExecutor]] 是一个 [[#concurrent.futures.Executor|Executor]] 子类,它使用线程池异步执行调用。
threads to execute calls asynchronously.
 
  
Deadlocks can occur when the callable associated with a [[#concurrent.futures.Future|<code>Future</code>]] waits on
+
当与 [[#concurrent.futures.Future|Future]] 关联的可调用对象等待另一个 [[#concurrent.futures.Future|Future]] 的结果时,可能会发生死锁。 例如:
the results of another [[#concurrent.futures.Future|<code>Future</code>]]. For example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第139行: 第105行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import time
+
<syntaxhighlight lang="python3">import time
 
def wait_on_b():
 
def wait_on_b():
 
     time.sleep(5)
 
     time.sleep(5)
第153行: 第119行:
 
executor = ThreadPoolExecutor(max_workers=2)
 
executor = ThreadPoolExecutor(max_workers=2)
 
a = executor.submit(wait_on_b)
 
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)</pre>
+
b = executor.submit(wait_on_a)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
And:
+
和:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第164行: 第130行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def wait_on_future():
+
<syntaxhighlight lang="python3">def wait_on_future():
 
     f = executor.submit(pow, 5, 2)
 
     f = executor.submit(pow, 5, 2)
 
     # This will never complete because there is only one worker thread and
 
     # This will never complete because there is only one worker thread and
第171行: 第137行:
  
 
executor = ThreadPoolExecutor(max_workers=1)
 
executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)</pre>
+
executor.submit(wait_on_future)</syntaxhighlight>
  
 
</div>
 
</div>
第177行: 第143行:
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt>''class'' <code>concurrent.futures.</code><code>ThreadPoolExecutor</code><span class="sig-paren">(</span>''<span class="n">max_workers</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">thread_name_prefix</span><span class="o">=</span><span class="default_value">''</span>'', ''<span class="n">initializer</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">initargs</span><span class="o">=</span><span class="default_value">()</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">ThreadPoolExecutor</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_workers</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">thread_name_prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span>'', ''<span class="n"><span class="pre">initializer</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">initargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">()</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>An [[#concurrent.futures.Executor|<code>Executor</code>]] subclass that uses a pool of at most ''max_workers''
+
<dd><p>[[#concurrent.futures.Executor|Executor]] 子类,最多使用 ''max_workers'' 个线程池异步执行调用。</p>
threads to execute calls asynchronously.</p>
+
<p>''initializer'' 是一个可选的可调用对象,在每个工作线程开始时调用; ''initargs'' 是传递给初始化程序的参数元组。 如果 ''initializer'' 引发异常,所有当前挂起的作业将引发 [[#concurrent.futures.thread.BrokenThreadPool|BrokenThreadPool]],以及任何向池提交更多作业的尝试。</p>
<p>''initializer'' is an optional callable that is called at the start of
 
each worker thread; ''initargs'' is a tuple of arguments passed to the
 
initializer. Should ''initializer'' raise an exception, all currently
 
pending jobs will raise a [[#concurrent.futures.thread.BrokenThreadPool|<code>BrokenThreadPool</code>]],
 
as well as any attempt to submit more jobs to the pool.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>If ''max_workers'' is <code>None</code> or
+
<p><span class="versionmodified changed">3.5版本变更:</span>如果''max_workers''<code>None</code>或不给,则默认为机器的处理器数,乘以<code>5</code> , 假设 [[#concurrent.futures.ThreadPoolExecutor|ThreadPoolExecutor]] 经常用于重叠 I/O 而不是 CPU 工作,并且工作人员的数量应该高于 [[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]] 的工作人员数量。</p>
not given, it will default to the number of processors on the machine,
 
multiplied by <code>5</code>, assuming that [[#concurrent.futures.ThreadPoolExecutor|<code>ThreadPoolExecutor</code>]] is often
 
used to overlap I/O instead of CPU work and the number of workers
 
should be higher than the number of workers
 
for [[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]].</p>
 
  
 
</div>
 
</div>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.6 新版功能: </span>The ''thread_name_prefix'' argument was added to allow users to
+
<p><span class="versionmodified added"> 3.6 版新功能: </span> 添加了 ''thread_name_prefix'' 参数以允许用户控制池创建的工作线程的 [[../threading#threading|threading.Thread]] 名称,以便于调试。</p>
control the [[../threading#threading|<code>threading.Thread</code>]] names for worker threads created by
 
the pool for easier debugging.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.7 版更改: </span>Added the ''initializer'' and ''initargs'' arguments.</p>
+
<p><span class="versionmodified changed"> 3.7 版更改: </span> 添加了 ''初始化器'' ''initargs'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.8 版更改: </span>Default value of ''max_workers'' is changed to <code>min(32, os.cpu_count() + 4)</code>.
+
<p><span class="versionmodified changed"> 3.8 版本变更: </span> ''max_workers'' 的默认值更改为 <code>min(32, os.cpu_count() + 4)</code>。 此默认值至少为 I/O 绑定任务保留 5 个工作线程。 它最多使用 32 CPU 内核来执行释放 GIL 的 CPU 绑定任务。 它避免在多核机器上隐式使用非常大的资源。</p>
This default value preserves at least 5 workers for I/O bound tasks.
+
<p>ThreadPoolExecutor 现在在启动 ''max_workers'' 工作线程之前重用空闲工作线程。</p>
It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL.
 
And it avoids using very large resources implicitly on many-core machines.</p>
 
<p>ThreadPoolExecutor now reuses idle worker threads before starting
 
''max_workers'' worker threads too.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第220行: 第170行:
 
<div id="threadpoolexecutor-example" class="section">
 
<div id="threadpoolexecutor-example" class="section">
  
<span id="id1"></span>
+
<span id="id5"></span>
=== ThreadPoolExecutor Example ===
+
=== 线程池执行器示例 ===
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第227行: 第177行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import concurrent.futures
+
<syntaxhighlight lang="python3">import concurrent.futures
 
import urllib.request
 
import urllib.request
  
第252行: 第202行:
 
             print('%r generated an exception: %s' % (url, exc))
 
             print('%r generated an exception: %s' % (url, exc))
 
         else:
 
         else:
             print('%r page is %d bytes' % (url, len(data)))</pre>
+
             print('%r page is %d bytes' % (url, len(data)))</syntaxhighlight>
  
 
</div>
 
</div>
第263行: 第213行:
 
<div id="processpoolexecutor" class="section">
 
<div id="processpoolexecutor" class="section">
  
== ProcessPoolExecutor ==
+
== 进程池执行器 ==
  
The [[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]] class is an [[#concurrent.futures.Executor|<code>Executor</code>]] subclass that
+
[[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]] 类是一个 [[#concurrent.futures.Executor|Executor]] 子类,它使用进程池异步执行调用。 [[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]] 使用 [[../multiprocessing#module-multiprocessing|multiprocessing]] 模块,这允许它绕过 [[../../glossary#term-global-interpreter-lock|Global Interpreter Lock]],但也意味着只能执行和返回可拾取的对象。
uses a pool of processes to execute calls asynchronously.
 
[[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]] uses the [[../multiprocessing#module-multiprocessing|<code>multiprocessing</code>]] module, which
 
allows it to side-step the [[../../glossary#term-global-interpreter-lock|<span class="xref std std-term">Global Interpreter Lock</span>]] but also means that
 
only picklable objects can be executed and returned.
 
  
The <code>__main__</code> module must be importable by worker subprocesses. This means
+
<code>__main__</code> 模块必须可由工作子进程导入。 这意味着 [[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]] 在交互式解释器中不起作用。
that [[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]] will not work in the interactive interpreter.
 
  
Calling [[#concurrent.futures.Executor|<code>Executor</code>]] or [[#concurrent.futures.Future|<code>Future</code>]] methods from a callable submitted
+
从提交给 [[#concurrent.futures.ProcessPoolExecutor|ProcessPoolExecutor]] 的可调用对象调用 [[#concurrent.futures.Executor|Executor]] [[#concurrent.futures.Future|Future]] 方法将导致死锁。
to a [[#concurrent.futures.ProcessPoolExecutor|<code>ProcessPoolExecutor</code>]] will result in deadlock.
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>concurrent.futures.</code><code>ProcessPoolExecutor</code><span class="sig-paren">(</span>''<span class="n">max_workers</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">mp_context</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">initializer</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">initargs</span><span class="o">=</span><span class="default_value">()</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">ProcessPoolExecutor</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">max_workers</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">mp_context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">initializer</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">initargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">()</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>An [[#concurrent.futures.Executor|<code>Executor</code>]] subclass that executes calls asynchronously using a pool
+
<dd><p>[[#concurrent.futures.Executor|Executor]] 子类使用最多 ''max_workers'' 个进程池异步执行调用。 如果 ''max_workers'' <code>None</code> 或未给出,则默认为机器上的处理器数量。 如果 ''max_workers'' 小于或等于 <code>0</code>,则会引发 [[../exceptions#ValueError|ValueError]]。 在 Windows 上,''max_workers'' 必须小于或等于 <code>61</code>。 如果不是,则将引发 [[../exceptions#ValueError|ValueError]]。 如果 ''max_workers'' <code>None</code>,则默认选择最多为 <code>61</code>,即使有更多处理器可用。 ''mp_context'' 可以是多处理上下文或无。 它将用于启动工作程序。 如果 ''mp_context'' <code>None</code> 或未给出,则使用默认的多处理上下文。</p>
of at most ''max_workers'' processes. If ''max_workers'' is <code>None</code> or not
+
<p>''initializer'' 是一个可选的可调用对象,在每个工作进程开始时调用; ''initargs'' 是传递给初始化程序的参数元组。 如果 ''initializer'' 引发异常,所有当前挂起的作业将引发 [[#concurrent.futures.process.BrokenProcessPool|BrokenProcessPool]],以及任何向池提交更多作业的尝试。</p>
given, it will default to the number of processors on the machine.
 
If ''max_workers'' is less than or equal to <code>0</code>, then a [[../exceptions#ValueError|<code>ValueError</code>]]
 
will be raised.
 
On Windows, ''max_workers'' must be less than or equal to <code>61</code>. If it is not
 
then [[../exceptions#ValueError|<code>ValueError</code>]] will be raised. If ''max_workers'' is <code>None</code>, then
 
the default chosen will be at most <code>61</code>, even if more processors are
 
available.
 
''mp_context'' can be a multiprocessing context or None. It will be used to
 
launch the workers. If ''mp_context'' is <code>None</code> or not given, the default
 
multiprocessing context is used.</p>
 
<p>''initializer'' is an optional callable that is called at the start of
 
each worker process; ''initargs'' is a tuple of arguments passed to the
 
initializer. Should ''initializer'' raise an exception, all currently
 
pending jobs will raise a [[#concurrent.futures.process.BrokenProcessPool|<code>BrokenProcessPool</code>]],
 
as well as any attempt to submit more jobs to the pool.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>When one of the worker processes terminates abruptly, a
+
<p><span class="versionmodified changed"> 3.3 版更改: </span> 当其中一个工作进程突然终止时,现在会引发 <code>BrokenProcessPool</code> 错误。 以前,行为是未定义的,但对 executor 或其期货的操作经常会冻结或死锁。</p>
<code>BrokenProcessPool</code> error is now raised. Previously, behaviour
 
was undefined but operations on the executor or its futures would often
 
freeze or deadlock.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.7 版更改: </span>The ''mp_context'' argument was added to allow users to control the
+
<p><span class="versionmodified changed"> 3.7 版更改: </span> 添加了 ''mp_context'' 参数以允许用户控制池创建的工作进程的 start_method。</p>
start_method for worker processes created by the pool.</p>
+
<p>添加了 ''initializer'' ''initargs'' 参数。</p>
<p>Added the ''initializer'' and ''initargs'' arguments.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第314行: 第239行:
 
<div id="processpoolexecutor-example" class="section">
 
<div id="processpoolexecutor-example" class="section">
  
<span id="id2"></span>
+
<span id="id6"></span>
=== ProcessPoolExecutor Example ===
+
=== ProcessPoolExecutor 示例 ===
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第321行: 第246行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import concurrent.futures
+
<syntaxhighlight lang="python3">import concurrent.futures
 
import math
 
import math
  
第333行: 第258行:
  
 
def is_prime(n):
 
def is_prime(n):
     if n &lt; 2:
+
     if n < 2:
 
         return False
 
         return False
 
     if n == 2:
 
     if n == 2:
第352行: 第277行:
  
 
if __name__ == '__main__':
 
if __name__ == '__main__':
     main()</pre>
+
     main()</syntaxhighlight>
  
 
</div>
 
</div>
第363行: 第288行:
 
<div id="future-objects" class="section">
 
<div id="future-objects" class="section">
  
== Future Objects ==
+
== 未来对象 ==
  
The [[#concurrent.futures.Future|<code>Future</code>]] class encapsulates the asynchronous execution of a callable.
+
[[#concurrent.futures.Future|Future]] 类封装了可调用的异步执行。 [[#concurrent.futures.Future|Future]] 实例由 [[#concurrent.futures.Executor.submit|Executor.submit()]] 创建。
[[#concurrent.futures.Future|<code>Future</code>]] instances are created by [[#concurrent.futures.Executor.submit|<code>Executor.submit()</code>]].
 
  
 
<dl>
 
<dl>
<dt>''class'' <code>concurrent.futures.</code><code>Future</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">Future</span></span></dt>
<dd><p>Encapsulates the asynchronous execution of a callable. [[#concurrent.futures.Future|<code>Future</code>]]
+
<dd><p>封装可调用的异步执行。 [[#concurrent.futures.Future|Future]] 实例由 [[#concurrent.futures.Executor.submit|Executor.submit()]] 创建,除测试外不应直接创建。</p>
instances are created by [[#concurrent.futures.Executor.submit|<code>Executor.submit()</code>]] and should not be created
 
directly except for testing.</p>
 
 
<blockquote><div>
 
<blockquote><div>
  
 
<dl>
 
<dl>
<dt><code>cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">cancel</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Attempt to cancel the call. If the call is currently being executed or
+
<dd><p>尝试取消呼叫。 如果调用当前正在执行或运行结束且无法取消,则该方法将返回 <code>False</code>,否则该调用将被取消,该方法将返回 <code>True</code></p></dd></dl>
finished running and cannot be cancelled then the method will return
 
<code>False</code>, otherwise the call will be cancelled and the method will
 
return <code>True</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">cancelled</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return <code>True</code> if the call was successfully cancelled.</p></dd></dl>
+
<dd><p>如果呼叫成功取消,则返回 <code>True</code></p></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>running</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">running</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return <code>True</code> if the call is currently being executed and cannot be
+
<dd><p>如果调用当前正在执行且无法取消,则返回 <code>True</code></p></dd></dl>
cancelled.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>done</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">done</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return <code>True</code> if the call was successfully cancelled or finished
+
<dd><p>如果调用成功取消或完成运行,则返回 <code>True</code></p></dd></dl>
running.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>result</code><span class="sig-paren">(</span>''<span class="n">timeout</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">result</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the value returned by the call. If the call hasn't yet completed
+
<dd><p>返回调用返回的值。 如果调用尚未完成,则此方法将等待 ''timeout'' 秒。 如果调用未在 ''timeout'' 秒内完成,则会引发 [[#concurrent.futures.TimeoutError|concurrent.futures.TimeoutError]]''timeout'' 可以是 int 或 float。 如果未指定 ''timeout'' <code>None</code>,则等待时间没有限制。</p>
then this method will wait up to ''timeout'' seconds. If the call hasn't
+
<p>如果未来在完成之前被取消,那么 [[#concurrent.futures.CancelledError|CancelledError]] 将被引发。</p>
completed in ''timeout'' seconds, then a
+
<p>如果调用引发异常,则此方法将引发相同的异常。</p></dd></dl>
[[#concurrent.futures.TimeoutError|<code>concurrent.futures.TimeoutError</code>]] will be raised. ''timeout'' can be
 
an int or float. If ''timeout'' is not specified or <code>None</code>, there is no
 
limit to the wait time.</p>
 
<p>If the future is cancelled before completing then [[#concurrent.futures.CancelledError|<code>CancelledError</code>]]
 
will be raised.</p>
 
<p>If the call raised, this method will raise the same exception.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>exception</code><span class="sig-paren">(</span>''<span class="n">timeout</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">exception</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return the exception raised by the call. If the call hasn't yet
+
<dd><p>返回调用引发的异常。 如果调用尚未完成,则此方法将等待 ''timeout'' 秒。 如果调用未在 ''timeout'' 秒内完成,则会引发 [[#concurrent.futures.TimeoutError|concurrent.futures.TimeoutError]]''timeout'' 可以是 int 或 float。 如果未指定 ''timeout'' <code>None</code>,则等待时间没有限制。</p>
completed then this method will wait up to ''timeout'' seconds. If the
+
<p>如果未来在完成之前被取消,那么 [[#concurrent.futures.CancelledError|CancelledError]] 将被引发。</p>
call hasn't completed in ''timeout'' seconds, then a
+
<p>如果调用完成而未引发,则返回 <code>None</code></p></dd></dl>
[[#concurrent.futures.TimeoutError|<code>concurrent.futures.TimeoutError</code>]] will be raised. ''timeout'' can be
 
an int or float. If ''timeout'' is not specified or <code>None</code>, there is no
 
limit to the wait time.</p>
 
<p>If the future is cancelled before completing then [[#concurrent.futures.CancelledError|<code>CancelledError</code>]]
 
will be raised.</p>
 
<p>If the call completed without raising, <code>None</code> is returned.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>add_done_callback</code><span class="sig-paren">(</span>''<span class="n">fn</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">add_done_callback</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fn</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Attaches the callable ''fn'' to the future. ''fn'' will be called, with the
+
<dd><p>将可调用的 ''fn'' 附加到未来。 ''fn'' 将在未来被取消或完成运行时被调用,未来作为其唯一参数。</p>
future as its only argument, when the future is cancelled or finishes
+
<p>添加的可调用对象按照添加的顺序调用,并且始终在属于添加它们的进程的线程中调用。 如果可调用对象引发 [[../exceptions#Exception|Exception]] 子类,它将被记录并忽略。 如果可调用对象引发 [[../exceptions#BaseException|BaseException]] 子类,则行为未定义。</p>
running.</p>
+
<p>如果future已经完成或被取消,会立即调用''fn''</p></dd></dl>
<p>Added callables are called in the order that they were added and are
 
always called in a thread belonging to the process that added them. If
 
the callable raises an [[../exceptions#Exception|<code>Exception</code>]] subclass, it will be logged and
 
ignored. If the callable raises a [[../exceptions#BaseException|<code>BaseException</code>]] subclass, the
 
behavior is undefined.</p>
 
<p>If the future has already completed or been cancelled, ''fn'' will be
 
called immediately.</p></dd></dl>
 
  
  
 
</div></blockquote>
 
</div></blockquote>
<p>The following [[#concurrent.futures.Future|<code>Future</code>]] methods are meant for use in unit tests and
+
<p>以下 [[#concurrent.futures.Future|Future]] 方法用于单元测试和 [[#concurrent.futures.Executor|Executor]] 实现。</p>
[[#concurrent.futures.Executor|<code>Executor</code>]] implementations.</p>
 
 
<blockquote><div>
 
<blockquote><div>
  
 
<dl>
 
<dl>
<dt><code>set_running_or_notify_cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">set_running_or_notify_cancel</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>This method should only be called by [[#concurrent.futures.Executor|<code>Executor</code>]] implementations
+
<dd><p>在执行与 [[#concurrent.futures.Future|Future]] 相关的工作和单元测试之前,该方法应该只被 [[#concurrent.futures.Executor|Executor]] 实现调用。</p>
before executing the work associated with the [[#concurrent.futures.Future|<code>Future</code>]] and by unit
+
<p>如果该方法返回 <code>False</code> 则取消 [[#concurrent.futures.Future|Future]],即 [[#concurrent.futures.Future.cancel|Future.cancel()]] 被调用并返回 True。 任何等待 [[#concurrent.futures.Future|Future]] 完成的线程(即 通过 [[#concurrent.futures.as_completed|as_completed()]] [[#concurrent.futures.wait|wait()]]) 将被唤醒。</p>
tests.</p>
+
<p>如果方法返回 <code>True</code> 则表示 [[#concurrent.futures.Future|Future]] 没有被取消并且已经进入运行状态,即 调用 [[#concurrent.futures.Future.running|Future.running()]] 将返回 True。</p>
<p>If the method returns <code>False</code> then the [[#concurrent.futures.Future|<code>Future</code>]] was cancelled,
+
<p>该方法只能调用一次,不能在调用 [[#concurrent.futures.Future.set_result|Future.set_result()]] [[#concurrent.futures.Future.set_exception|Future.set_exception()]] 后调用。</p></dd></dl>
i.e. [[#concurrent.futures.Future.cancel|<code>Future.cancel()</code>]] was called and returned True. Any threads
 
waiting on the [[#concurrent.futures.Future|<code>Future</code>]] completing (i.e. through
 
[[#concurrent.futures.as_completed|<code>as_completed()</code>]] or [[#concurrent.futures.wait|<code>wait()</code>]]) will be woken up.</p>
 
<p>If the method returns <code>True</code> then the [[#concurrent.futures.Future|<code>Future</code>]] was not cancelled
 
and has been put in the running state, i.e. calls to
 
[[#concurrent.futures.Future.running|<code>Future.running()</code>]] will return True.</p>
 
<p>This method can only be called once and cannot be called after
 
[[#concurrent.futures.Future.set_result|<code>Future.set_result()</code>]] or [[#concurrent.futures.Future.set_exception|<code>Future.set_exception()</code>]] have been
 
called.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>set_result</code><span class="sig-paren">(</span>''<span class="n">result</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">set_result</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">result</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Sets the result of the work associated with the [[#concurrent.futures.Future|<code>Future</code>]] to
+
<dd><p>将与 [[#concurrent.futures.Future|Future]] 相关的工作结果设置为 ''result''</p>
''result''.</p>
+
<p>此方法仅应由 [[#concurrent.futures.Executor|Executor]] 实现和单元测试使用。</p>
<p>This method should only be used by [[#concurrent.futures.Executor|<code>Executor</code>]] implementations and
 
unit tests.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.8 版更改: </span>This method raises
+
<p><span class="versionmodified changed"> 在 3.8 版更改: </span> 如果 [[#concurrent.futures.Future|Future]] 已经完成,此方法会引发 [[#concurrent.futures.InvalidStateError|concurrent.futures.InvalidStateError]]</p>
[[#concurrent.futures.InvalidStateError|<code>concurrent.futures.InvalidStateError</code>]] if the [[#concurrent.futures.Future|<code>Future</code>]] is
 
already done.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>set_exception</code><span class="sig-paren">(</span>''<span class="n">exception</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">set_exception</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">exception</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Sets the result of the work associated with the [[#concurrent.futures.Future|<code>Future</code>]] to the
+
<dd><p>将与 [[#concurrent.futures.Future|Future]] 相关的工作结果设置为 [[../exceptions#Exception|Exception]] ''exception''</p>
[[../exceptions#Exception|<code>Exception</code>]] ''exception''.</p>
+
<p>此方法仅应由 [[#concurrent.futures.Executor|Executor]] 实现和单元测试使用。</p>
<p>This method should only be used by [[#concurrent.futures.Executor|<code>Executor</code>]] implementations and
 
unit tests.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.8 版更改: </span>This method raises
+
<p><span class="versionmodified changed"> 在 3.8 版更改: </span> 如果 [[#concurrent.futures.Future|Future]] 已经完成,此方法会引发 [[#concurrent.futures.InvalidStateError|concurrent.futures.InvalidStateError]]</p>
[[#concurrent.futures.InvalidStateError|<code>concurrent.futures.InvalidStateError</code>]] if the [[#concurrent.futures.Future|<code>Future</code>]] is
 
already done.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第490行: 第370行:
 
<div id="module-functions" class="section">
 
<div id="module-functions" class="section">
  
== Module Functions ==
+
== 模块功能 ==
  
 
<dl>
 
<dl>
<dt><code>concurrent.futures.</code><code>wait</code><span class="sig-paren">(</span>''<span class="n">fs</span>'', ''<span class="n">timeout</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">return_when</span><span class="o">=</span><span class="default_value">ALL_COMPLETED</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fs</span></span>'', ''<span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">return_when</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ALL_COMPLETED</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Wait for the [[#concurrent.futures.Future|<code>Future</code>]] instances (possibly created by different
+
<dd><p>等待 ''fs'' 给出的 [[#concurrent.futures.Future|Future]] 实例(可能由不同的 [[#concurrent.futures.Executor|Executor]] 实例创建)完成。 返回一个命名的 2 元组集合。 第一组名为 <code>done</code>,包含在等待完成之前完成的期货(已完成或取消的期货)。 第二组名为 <code>not_done</code>,包含未完成的期货(待定或正在运行的期货)。</p>
[[#concurrent.futures.Executor|<code>Executor</code>]] instances) given by ''fs'' to complete. Returns a named
+
<p>''timeout'' 可用于控制返回前等待的最大秒数。 ''timeout'' 可以是 int 或 float。 如果未指定 ''timeout'' <code>None</code>,则等待时间没有限制。</p>
2-tuple of sets. The first set, named <code>done</code>, contains the futures that
+
<p>''return_when'' 指示此函数应何时返回。 它必须是以下常量之一:</p>
completed (finished or cancelled futures) before the wait completed. The
 
second set, named <code>not_done</code>, contains the futures that did not complete
 
(pending or running futures).</p>
 
<p>''timeout'' can be used to control the maximum number of seconds to wait before
 
returning. ''timeout'' can be an int or float. If ''timeout'' is not specified
 
or <code>None</code>, there is no limit to the wait time.</p>
 
<p>''return_when'' indicates when this function should return. It must be one of
 
the following constants:</p>
 
 
{|
 
{|
!width="42%"| <p>Constant</p>
+
!width="42%"| <p>持续的</p>
!width="57%"| <p>Description</p>
+
!width="57%"| <p>描述</p>
 
|-
 
|-
 
| <p><code>FIRST_COMPLETED</code></p>
 
| <p><code>FIRST_COMPLETED</code></p>
| <p>The function will return when any
+
| <p>当任何未来完成或取消时,该函数将返回。</p>
future finishes or is cancelled.</p>
 
 
|-
 
|-
 
| <p><code>FIRST_EXCEPTION</code></p>
 
| <p><code>FIRST_EXCEPTION</code></p>
| <p>The function will return when any
+
| <p>当任何未来通过引发异常完成时,该函数将返回。 如果没有 future 引发异常,则它相当于 <code>ALL_COMPLETED</code></p>
future finishes by raising an
 
exception. If no future raises an
 
exception then it is equivalent to
 
<code>ALL_COMPLETED</code>.</p>
 
 
|-
 
|-
 
| <p><code>ALL_COMPLETED</code></p>
 
| <p><code>ALL_COMPLETED</code></p>
| <p>The function will return when all
+
| <p>当所有期货完成或被取消时,该函数将返回。</p>
futures finish or are cancelled.</p>
 
 
|}
 
|}
 
</dd></dl>
 
</dd></dl>
  
; <code>concurrent.futures.</code><code>as_completed</code><span class="sig-paren">(</span>''<span class="n">fs</span>'', ''<span class="n">timeout</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">as_completed</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fs</span></span>'', ''<span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
: Returns an iterator over the [[#concurrent.futures.Future|<code>Future</code>]] instances (possibly created by different [[#concurrent.futures.Executor|<code>Executor</code>]] instances) given by ''fs'' that yields futures as they complete (finished or cancelled futures). Any futures given by ''fs'' that are duplicated will be returned once. Any futures that completed before [[#concurrent.futures.as_completed|<code>as_completed()</code>]] is called will be yielded first. The returned iterator raises a [[#concurrent.futures.TimeoutError|<code>concurrent.futures.TimeoutError</code>]] if [[../stdtypes#iterator|<code>__next__()</code>]] is called and the result isn't available after ''timeout'' seconds from the original call to [[#concurrent.futures.as_completed|<code>as_completed()</code>]]. ''timeout'' can be an int or float. If ''timeout'' is not specified or <code>None</code>, there is no limit to the wait time.
+
: 返回由 ''fs'' 给出的 [[#concurrent.futures.Future|Future]] 实例(可能由不同的 [[#concurrent.futures.Executor|Executor]] 实例创建)的迭代器,它在完成时产生期货(已完成或取消的期货)。 ''fs'' 给出的任何重复的期货将返回一次。 在调用 [[#concurrent.futures.as_completed|as_completed()]] 之前完成的任何期货将首先产生。 如果调用了 [[../stdtypes#iterator|__next__()]] 并且在 ''timeout'' 秒后结果不可用,则返回的迭代器会引发 [[#concurrent.futures.TimeoutError|concurrent.futures.TimeoutError]] X193X]as_completed()''timeout'' 可以是 int 或 float。 如果未指定 ''timeout'' <code>None</code>,则等待时间没有限制。
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-3148 '''PEP 3148'''] -- futures - execute computations asynchronously
+
; <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-3148 PEP 3148] – 期货 – 异步执行计算
: The proposal which described this feature for inclusion in the Python standard library.
+
: 描述此功能以包含在 Python 标准库中的提案。
  
  
第542行: 第408行:
 
<div id="exception-classes" class="section">
 
<div id="exception-classes" class="section">
  
== Exception classes ==
+
== 异常类 ==
  
; ''exception'' <code>concurrent.futures.</code><code>CancelledError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">CancelledError</span></span>
: Raised when a future is cancelled.
+
: 在取消未来时引发。
  
; ''exception'' <code>concurrent.futures.</code><code>TimeoutError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">TimeoutError</span></span>
: Raised when a future operation exceeds the given timeout.
+
: 当未来的操作超过给定的超时时引发。
  
 
<dl>
 
<dl>
<dt>''exception'' <code>concurrent.futures.</code><code>BrokenExecutor</code></dt>
+
<dt>''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">BrokenExecutor</span></span></dt>
<dd><p>Derived from [[../exceptions#RuntimeError|<code>RuntimeError</code>]], this exception class is raised
+
<dd><p>派生自 [[../exceptions#RuntimeError|RuntimeError]],该异常类在 executor 因某种原因损坏时引发,不能用于提交或执行新任务。</p>
when an executor is broken for some reason, and cannot be used
 
to submit or execute new tasks.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.7 新版功能.</span></p>
+
<p><span class="versionmodified added">3.7 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt>''exception'' <code>concurrent.futures.</code><code>InvalidStateError</code></dt>
+
<dt>''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.</span></span><span class="sig-name descname"><span class="pre">InvalidStateError</span></span></dt>
<dd><p>Raised when an operation is performed on a future that is not allowed
+
<dd><p>在当前状态不允许的未来上执行操作时引发。</p>
in the current state.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.8 新版功能.</span></p>
+
<p><span class="versionmodified added">3.8 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt>''exception'' <code>concurrent.futures.thread.</code><code>BrokenThreadPool</code></dt>
+
<dt>''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.thread.</span></span><span class="sig-name descname"><span class="pre">BrokenThreadPool</span></span></dt>
<dd><p>Derived from [[#concurrent.futures.BrokenExecutor|<code>BrokenExecutor</code>]], this exception
+
<dd><p>派生自 [[#concurrent.futures.BrokenExecutor|BrokenExecutor]],当 <code>ThreadPoolExecutor</code> 的工作人员之一初始化失败时,会引发此异常类。</p>
class is raised when one of the workers of a <code>ThreadPoolExecutor</code>
 
has failed initializing.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.7 新版功能.</span></p>
+
<p><span class="versionmodified added">3.7 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt>''exception'' <code>concurrent.futures.process.</code><code>BrokenProcessPool</code></dt>
+
<dt>''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">concurrent.futures.process.</span></span><span class="sig-name descname"><span class="pre">BrokenProcessPool</span></span></dt>
<dd><p>Derived from [[#concurrent.futures.BrokenExecutor|<code>BrokenExecutor</code>]] (formerly
+
<dd><p>派生自 [[#concurrent.futures.BrokenExecutor|BrokenExecutor]](以前称为 [[../exceptions#RuntimeError|RuntimeError]]),当 <code>ProcessPoolExecutor</code> 的一个工作程序以非干净方式终止时(例如,如果它是从外面杀死的)。</p>
[[../exceptions#RuntimeError|<code>RuntimeError</code>]]), this exception class is raised when one of the
 
workers of a <code>ProcessPoolExecutor</code> has terminated in a non-clean
 
fashion (for example, if it was killed from the outside).</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.3 新版功能.</span></p>
+
<p><span class="versionmodified added">3.3 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第596行: 第454行:
  
 
</div>
 
</div>
 +
 +
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

concurrent.futures — 启动并行任务

3.2 版中的新功能。


源代码: :source:`Lib/concurrent/futures/thread.py` and :source:`Lib/concurrent/futures/process.py`



concurrent.futures 模块为异步执行可调用对象提供了一个高级接口。

异步执行可以使用线程执行,使用 ThreadPoolExecutor,或单独的进程,使用 ProcessPoolExecutor。 两者都实现了相同的接口,该接口由抽象的 Executor 类定义。

执行器对象

class concurrent.futures.Executor

一个抽象类,提供异步执行调用的方法。 它不应直接使用,而应通过其具体的子类使用。

submit(fn, /, *args, **kwargs)

安排可调用对象 fnfn(*args **kwargs) 的形式执行,并返回一个表示可调用对象执行的 Future 对象。

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())
map(func, *iterables, timeout=None, chunksize=1)

类似于 map(func, *iterables) 除了:

  • iterables 立即收集而不是懒惰;

  • func 是异步执行的,并且可以同时调用多个 func

如果调用了 __next__() 并且在 timeout 秒后结果不可用,则返回的迭代器会引发 concurrent.futures.TimeoutError X193X]Executor.map()。 timeout 可以是 int 或 float。 如果未指定 timeoutNone,则等待时间没有限制。

如果 func 调用引发异常,则在从迭代器检索其值时将引发该异常。

当使用 ProcessPoolExecutor 时,这个方法将 iterables 分成许多块,作为单独的任务提交到池中。 这些块的(近似)大小可以通过将 chunksize 设置为正整数来指定。 对于非常长的可迭代对象,与默认大小 1 相比,使用较大的 chunksize 值可以显着提高性能。 使用 ThreadPoolExecutorchunksize 无效。

3.5 版更改: 添加 chunksize 参数。

shutdown(wait=True, *, cancel_futures=False)

当当前挂起的期货完成执行时,通知执行器它应该释放它正在使用的任何资源。 关闭后调用 Executor.submit()Executor.map() 将引发 RuntimeError

如果 waitTrue 则此方法将不会返回,直到所有挂起的期货都执行完毕并且与执行程序关联的资源已被释放。 如果 waitFalse 则此方法将立即返回,并且当所有挂起的期货执行完毕后,与执行器关联的资源将被释放。 无论 wait 的值如何,在所有挂起的期货执行完毕之前,整个 Python 程序都不会退出。

如果 cancel_futuresTrue,则此方法将取消所有执行者尚未开始运行的挂起期货。 无论 cancel_futures 的值如何,任何已完成或正在运行的期货都不会被取消。

如果 cancel_futureswait 都是 True,则执行器已开始运行的所有期货将在此方法返回之前完成。 剩余的期货被取消。

如果您使用 with 语句,您可以避免显式调用此方法,这将关闭 Executor(等待好像 Executor.shutdown() 被调用wait 设置为 True):

import shutil
with ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src4.txt', 'dest4.txt')

3.9 版变更: 添加 cancel_futures



线程池执行器

ThreadPoolExecutor 是一个 Executor 子类,它使用线程池异步执行调用。

当与 Future 关联的可调用对象等待另一个 Future 的结果时,可能会发生死锁。 例如:

import time
def wait_on_b():
    time.sleep(5)
    print(b.result())  # b will never complete because it is waiting on a.
    return 5

def wait_on_a():
    time.sleep(5)
    print(a.result())  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)

和:

def wait_on_future():
    f = executor.submit(pow, 5, 2)
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print(f.result())

executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)
class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix=, initializer=None, initargs=())

Executor 子类,最多使用 max_workers 个线程池异步执行调用。

initializer 是一个可选的可调用对象,在每个工作线程开始时调用; initargs 是传递给初始化程序的参数元组。 如果 initializer 引发异常,所有当前挂起的作业将引发 BrokenThreadPool,以及任何向池提交更多作业的尝试。

3.5版本变更:如果max_workersNone或不给,则默认为机器的处理器数,乘以5 , 假设 ThreadPoolExecutor 经常用于重叠 I/O 而不是 CPU 工作,并且工作人员的数量应该高于 ProcessPoolExecutor 的工作人员数量。

3.6 版新功能: 添加了 thread_name_prefix 参数以允许用户控制池创建的工作线程的 threading.Thread 名称,以便于调试。

3.7 版更改: 添加了 初始化器initargs 参数。

3.8 版本变更: max_workers 的默认值更改为 min(32, os.cpu_count() + 4)。 此默认值至少为 I/O 绑定任务保留 5 个工作线程。 它最多使用 32 个 CPU 内核来执行释放 GIL 的 CPU 绑定任务。 它避免在多核机器上隐式使用非常大的资源。

ThreadPoolExecutor 现在在启动 max_workers 工作线程之前重用空闲工作线程。

线程池执行器示例

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

进程池执行器

ProcessPoolExecutor 类是一个 Executor 子类,它使用进程池异步执行调用。 ProcessPoolExecutor 使用 multiprocessing 模块,这允许它绕过 Global Interpreter Lock,但也意味着只能执行和返回可拾取的对象。

__main__ 模块必须可由工作子进程导入。 这意味着 ProcessPoolExecutor 在交互式解释器中不起作用。

从提交给 ProcessPoolExecutor 的可调用对象调用 ExecutorFuture 方法将导致死锁。

class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None, initializer=None, initargs=())

Executor 子类使用最多 max_workers 个进程池异步执行调用。 如果 max_workersNone 或未给出,则默认为机器上的处理器数量。 如果 max_workers 小于或等于 0,则会引发 ValueError。 在 Windows 上,max_workers 必须小于或等于 61。 如果不是,则将引发 ValueError。 如果 max_workersNone,则默认选择最多为 61,即使有更多处理器可用。 mp_context 可以是多处理上下文或无。 它将用于启动工作程序。 如果 mp_contextNone 或未给出,则使用默认的多处理上下文。

initializer 是一个可选的可调用对象,在每个工作进程开始时调用; initargs 是传递给初始化程序的参数元组。 如果 initializer 引发异常,所有当前挂起的作业将引发 BrokenProcessPool,以及任何向池提交更多作业的尝试。

3.3 版更改: 当其中一个工作进程突然终止时,现在会引发 BrokenProcessPool 错误。 以前,行为是未定义的,但对 executor 或其期货的操作经常会冻结或死锁。

3.7 版更改: 添加了 mp_context 参数以允许用户控制池创建的工作进程的 start_method。

添加了 initializerinitargs 参数。

ProcessPoolExecutor 示例

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

未来对象

Future 类封装了可调用的异步执行。 Future 实例由 Executor.submit() 创建。

class concurrent.futures.Future

封装可调用的异步执行。 Future 实例由 Executor.submit() 创建,除测试外不应直接创建。

cancel()

尝试取消呼叫。 如果调用当前正在执行或运行结束且无法取消,则该方法将返回 False,否则该调用将被取消,该方法将返回 True

cancelled()

如果呼叫成功取消,则返回 True

running()

如果调用当前正在执行且无法取消,则返回 True

done()

如果调用成功取消或完成运行,则返回 True

result(timeout=None)

返回调用返回的值。 如果调用尚未完成,则此方法将等待 timeout 秒。 如果调用未在 timeout 秒内完成,则会引发 concurrent.futures.TimeoutErrortimeout 可以是 int 或 float。 如果未指定 timeoutNone,则等待时间没有限制。

如果未来在完成之前被取消,那么 CancelledError 将被引发。

如果调用引发异常,则此方法将引发相同的异常。

exception(timeout=None)

返回调用引发的异常。 如果调用尚未完成,则此方法将等待 timeout 秒。 如果调用未在 timeout 秒内完成,则会引发 concurrent.futures.TimeoutErrortimeout 可以是 int 或 float。 如果未指定 timeoutNone,则等待时间没有限制。

如果未来在完成之前被取消,那么 CancelledError 将被引发。

如果调用完成而未引发,则返回 None

add_done_callback(fn)

将可调用的 fn 附加到未来。 fn 将在未来被取消或完成运行时被调用,未来作为其唯一参数。

添加的可调用对象按照添加的顺序调用,并且始终在属于添加它们的进程的线程中调用。 如果可调用对象引发 Exception 子类,它将被记录并忽略。 如果可调用对象引发 BaseException 子类,则行为未定义。

如果future已经完成或被取消,会立即调用fn


以下 Future 方法用于单元测试和 Executor 实现。

set_running_or_notify_cancel()

在执行与 Future 相关的工作和单元测试之前,该方法应该只被 Executor 实现调用。

如果该方法返回 False 则取消 Future,即 Future.cancel() 被调用并返回 True。 任何等待 Future 完成的线程(即 通过 as_completed()wait()) 将被唤醒。

如果方法返回 True 则表示 Future 没有被取消并且已经进入运行状态,即 调用 Future.running() 将返回 True。

该方法只能调用一次,不能在调用 Future.set_result()Future.set_exception() 后调用。

set_result(result)

将与 Future 相关的工作结果设置为 result

此方法仅应由 Executor 实现和单元测试使用。

在 3.8 版更改: 如果 Future 已经完成,此方法会引发 concurrent.futures.InvalidStateError

set_exception(exception)

将与 Future 相关的工作结果设置为 Exception exception

此方法仅应由 Executor 实现和单元测试使用。

在 3.8 版更改: 如果 Future 已经完成,此方法会引发 concurrent.futures.InvalidStateError



模块功能

concurrent.futures.wait(fs, timeout=None, return_when=ALL_COMPLETED)

等待 fs 给出的 Future 实例(可能由不同的 Executor 实例创建)完成。 返回一个命名的 2 元组集合。 第一组名为 done,包含在等待完成之前完成的期货(已完成或取消的期货)。 第二组名为 not_done,包含未完成的期货(待定或正在运行的期货)。

timeout 可用于控制返回前等待的最大秒数。 timeout 可以是 int 或 float。 如果未指定 timeoutNone,则等待时间没有限制。

return_when 指示此函数应何时返回。 它必须是以下常量之一:

持续的

描述

FIRST_COMPLETED

当任何未来完成或取消时,该函数将返回。

FIRST_EXCEPTION

当任何未来通过引发异常完成时,该函数将返回。 如果没有 future 引发异常,则它相当于 ALL_COMPLETED

ALL_COMPLETED

当所有期货完成或被取消时,该函数将返回。

concurrent.futures.as_completed(fs, timeout=None)
返回由 fs 给出的 Future 实例(可能由不同的 Executor 实例创建)的迭代器,它在完成时产生期货(已完成或取消的期货)。 fs 给出的任何重复的期货将返回一次。 在调用 as_completed() 之前完成的任何期货将首先产生。 如果调用了 __next__() 并且在 timeout 秒后结果不可用,则返回的迭代器会引发 concurrent.futures.TimeoutError X193X]as_completed()。 timeout 可以是 int 或 float。 如果未指定 timeoutNone,则等待时间没有限制。

也可以看看

PEP 3148 – 期货 – 异步执行计算
描述此功能以包含在 Python 标准库中的提案。


异常类

exception concurrent.futures.CancelledError
在取消未来时引发。
exception concurrent.futures.TimeoutError
当未来的操作超过给定的超时时引发。
exception concurrent.futures.BrokenExecutor

派生自 RuntimeError,该异常类在 executor 因某种原因损坏时引发,不能用于提交或执行新任务。

3.7 版中的新功能。

exception concurrent.futures.InvalidStateError

在当前状态不允许的未来上执行操作时引发。

3.8 版中的新功能。

exception concurrent.futures.thread.BrokenThreadPool

派生自 BrokenExecutor,当 ThreadPoolExecutor 的工作人员之一初始化失败时,会引发此异常类。

3.7 版中的新功能。

exception concurrent.futures.process.BrokenProcessPool

派生自 BrokenExecutor(以前称为 RuntimeError),当 ProcessPoolExecutor 的一个工作程序以非干净方式终止时(例如,如果它是从外面杀死的)。

3.3 版中的新功能。