Python线程池及其原理和使用(超级详细)
<p>系统启动一个新线程的成本是比较高的,因为它涉及与操作系统的交互。在这种情形下,使用线程池可以很好地提升性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更应该考虑使用线程池。<br><br>线程池在系统启动时即创建大量空闲的线程,程序只要将一个函数提交给线程池,线程池就会启动一个空闲的线程来执行它。当该函数执行结束后,该线程并不会死亡,而是再次返回到线程池中变成空闲状态,等待执行下一个函数。<br><br>此外,使用线程池可以有效地控制系统中并发线程的数量。当系统中包含有大量的并发线程时,会导致系统性能急剧下降,甚至导致 Python 解释器崩溃,而线程池的最大线程数参数可以控制系统中并发线程的数量不超过此数。</p><h2>线程池的使用</h2>
<p>
线程池的基类是 concurrent.futures 模块中的 Executor,Executor 提供了两个子类,即 ThreadPoolExecutor 和 ProcessPoolExecutor,其中 ThreadPoolExecutor 用于创建线程池,而 ProcessPoolExecutor 用于创建进程池。<br><br>如果使用线程池/进程池来管理并发编程,那么只要将相应的 task 函数提交给线程池/进程池,剩下的事情就由线程池/进程池来搞定。<br><br>Exectuor 提供了如下常用方法:</p>
<ul>
<li>submit(fn, *args, **kwargs):将 fn 函数提交给线程池。*args 代表传给 fn 函数的参数,*kwargs 代表以关键字参数的形式为 fn 函数传入参数。</li>
<li>map(func, *iterables, timeout=None, chunksize=1):该函数类似于全局函数 map(func, *iterables),只是该函数将会启动多个线程,以异步方式立即对 iterables 执行 map 处理。</li>
<li>shutdown(wait=True):关闭线程池。</li>
</ul>
<p>
<br>程序将 task 函数提交(submit)给线程池后,submit 方法会返回一个 Future 对象,Future 类主要用于获取线程任务函数的返回值。由于线程任务会在新线程中以异步方式执行,因此,线程执行的函数相当于一个“将来完成”的任务,所以 Python 使用 Future 来代表。</p>
<p class="info-box">Future 提供了如下方法:</p>
<ul>
<li>cancel():取消该 Future 代表的线程任务。如果该任务正在执行,不可取消,则该方法返回 False;否则,程序会取消该任务,并返回 True。</li>
<li>cancelled():返回 Future 代表的线程任务是否被成功取消。</li>
<li>running():如果该 Future 代表的线程任务正在执行、不可被取消,该方法返回 True。</li>
<li>done():如果该 Funture 代表的线程任务被成功取消或执行完成,则该方法返回 True。</li>
<li>result(timeout=None):获取该 Future 代表的线程任务最后返回的结果。如果 Future 代表的线程任务还未完成,该方法将会阻塞当前线程,其中 timeout 参数指定最多阻塞多少秒。</li>
<li>exception(timeout=None):获取该 Future 代表的线程任务所引发的异常。如果该任务成功完成,没有异常,则该方法返回 None。</li>
<li>add_done_callback(fn):为该 Future 代表的线程任务注册一个“回调函数”,当该任务成功完成时,程序会自动触发该 fn 函数。</li>
</ul>
<p>
<br>在用完一个线程池后,应该调用该线程池的 shutdown() 方法,该方法将启动线程池的关闭序列。调用 shutdown() 方法后的线程池不再接收新任务,但会将以前所有的已提交任务执行完成。当线程池中的所有任务都执行完成后,该线程池中的所有线程都会死亡。<br><br>使用线程池来执行线程任务的步骤如下:</p>
<ol>
<li>调用 ThreadPoolExecutor 类的构造器创建一个线程池。</li>
<li>定义一个普通函数作为线程任务。</li>
<li>调用 ThreadPoolExecutor 对象的 submit() 方法来提交线程任务。</li>
<li>当不想提交任何任务时,调用 ThreadPoolExecutor 对象的 shutdown() 方法来关闭线程池。</li>
</ol>
<p><br>下面程序示范了如何使用线程池来执行线程任务:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)"> 1</span> <span style="color: rgba(0, 0, 255, 1)">def</span> test(value1, value2=<span style="color: rgba(0, 0, 0, 1)">None):
</span><span style="color: rgba(0, 128, 128, 1)"> 2</span> <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">%s threading is printed %s, %s</span><span style="color: rgba(128, 0, 0, 1)">"</span>%<span style="color: rgba(0, 0, 0, 1)">(threading.current_thread().name, value1, value2))
</span><span style="color: rgba(0, 128, 128, 1)"> 3</span> time.sleep(2<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 128, 1)"> 4</span> <span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">finished</span><span style="color: rgba(128, 0, 0, 1)">'</span>
<span style="color: rgba(0, 128, 128, 1)"> 5</span>
<span style="color: rgba(0, 128, 128, 1)"> 6</span> <span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> test_result(future):
</span><span style="color: rgba(0, 128, 128, 1)"> 7</span> <span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(future.result())
</span><span style="color: rgba(0, 128, 128, 1)"> 8</span>
<span style="color: rgba(0, 128, 128, 1)"> 9</span> <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(128, 0, 128, 1)">__name__</span> == <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__main__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">:
</span><span style="color: rgba(0, 128, 128, 1)">10</span> <span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> numpy as np
</span><span style="color: rgba(0, 128, 128, 1)">11</span> <span style="color: rgba(0, 0, 255, 1)">from</span> concurrent.futures <span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> ThreadPoolExecutor
</span><span style="color: rgba(0, 128, 128, 1)">12</span> threadPool = ThreadPoolExecutor(max_workers=4, thread_name_prefix=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">test_</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 128, 1)">13</span> <span style="color: rgba(0, 0, 255, 1)">for</span> i <span style="color: rgba(0, 0, 255, 1)">in</span> range(0,10<span style="color: rgba(0, 0, 0, 1)">):
</span><span style="color: rgba(0, 128, 128, 1)">14</span> future = threadPool.submit(test, i,i+1<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 128, 1)">15</span>
<span style="color: rgba(0, 128, 128, 1)">16</span> threadPool.shutdown(wait=True)</pre>
</div>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)">1</span> <span style="color: rgba(0, 0, 0, 1)">结果:
</span><span style="color: rgba(0, 128, 128, 1)">2</span>
<span style="color: rgba(0, 128, 128, 1)">3</span> test__0 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 0, 1
<span style="color: rgba(0, 128, 128, 1)">4</span> test__1 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 1, 2
<span style="color: rgba(0, 128, 128, 1)">5</span> test__2 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 2, 3
<span style="color: rgba(0, 128, 128, 1)">6</span> test__3 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 3, 4
<span style="color: rgba(0, 128, 128, 1)">7</span> test__1 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 4, 5
<span style="color: rgba(0, 128, 128, 1)">8</span> test__0 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 5, 6
<span style="color: rgba(0, 128, 128, 1)">9</span> test__3 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 6, 7</pre>
</div>
<p> </p>
<h2>获取执行结果</h2>
<p><span style="font-size: 15px">
前面程序调用了 Future 的 result() 方法来获取线程任务的运回值,但该方法会阻塞当前主线程,只有等到钱程任务完成后,result() 方法的阻塞才会被解除。</span><br><br><span style="font-size: 15px">如果程序不希望直接调用 result() 方法阻塞线程,则可通过 Future 的 add_done_callback() 方法来添加回调函数,该回调函数形如 fn(future)。当线程任务完成后,程序会自动触发该回调函数,并将对应的 Future 对象作为参数传给该回调函数。</span><br><span style="font-size: 15px">直接调用result函数结果</span></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)"> 1</span> <span style="color: rgba(0, 0, 255, 1)">def</span> test(value1, value2=<span style="color: rgba(0, 0, 0, 1)">None):
</span><span style="color: rgba(0, 128, 128, 1)"> 2</span> <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">%s threading is printed %s, %s</span><span style="color: rgba(128, 0, 0, 1)">"</span>%<span style="color: rgba(0, 0, 0, 1)">(threading.current_thread().name, value1, value2))
</span><span style="color: rgba(0, 128, 128, 1)"> 3</span> time.sleep(2<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 128, 1)"> 4</span> <span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">finished</span><span style="color: rgba(128, 0, 0, 1)">'</span>
<span style="color: rgba(0, 128, 128, 1)"> 5</span>
<span style="color: rgba(0, 128, 128, 1)"> 6</span> <span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> test_result(future):
</span><span style="color: rgba(0, 128, 128, 1)"> 7</span> <span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(future.result())
</span><span style="color: rgba(0, 128, 128, 1)"> 8</span>
<span style="color: rgba(0, 128, 128, 1)"> 9</span> <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(128, 0, 128, 1)">__name__</span> == <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__main__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">:
</span><span style="color: rgba(0, 128, 128, 1)">10</span> <span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> numpy as np
</span><span style="color: rgba(0, 128, 128, 1)">11</span> <span style="color: rgba(0, 0, 255, 1)">from</span> concurrent.futures <span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> ThreadPoolExecutor
</span><span style="color: rgba(0, 128, 128, 1)">12</span> threadPool = ThreadPoolExecutor(max_workers=4, thread_name_prefix=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">test_</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 128, 1)">13</span> <span style="color: rgba(0, 0, 255, 1)">for</span> i <span style="color: rgba(0, 0, 255, 1)">in</span> range(0,10<span style="color: rgba(0, 0, 0, 1)">):
</span><span style="color: rgba(0, 128, 128, 1)">14</span> future = threadPool.submit(test, i,i+1<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 128, 128, 1)">15</span> <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> future.add_done_callback(test_result)</span>
<span style="color: rgba(0, 128, 128, 1)">16</span> <span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(future.result())
</span><span style="color: rgba(0, 128, 128, 1)">17</span>
<span style="color: rgba(0, 128, 128, 1)">18</span> threadPool.shutdown(wait=<span style="color: rgba(0, 0, 0, 1)">True)
</span><span style="color: rgba(0, 128, 128, 1)">19</span> <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">main finished</span><span style="color: rgba(128, 0, 0, 1)">'</span>)</pre>
</div>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)">1</span> <span style="color: rgba(0, 0, 0, 1)">结果:
</span><span style="color: rgba(0, 128, 128, 1)">2</span>
<span style="color: rgba(0, 128, 128, 1)">3</span> test__0 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 0, 1
<span style="color: rgba(0, 128, 128, 1)">4</span> <span style="color: rgba(0, 0, 0, 1)">finished
</span><span style="color: rgba(0, 128, 128, 1)">5</span> test__0 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 1, 2
<span style="color: rgba(0, 128, 128, 1)">6</span> <span style="color: rgba(0, 0, 0, 1)">finished
</span><span style="color: rgba(0, 128, 128, 1)">7</span> test__1 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 2, 3
<span style="color: rgba(0, 128, 128, 1)">8</span> finished</pre>
</div>
<p><span style="font-size: 15px">去掉上面注释部分,调用future.add_done_callback函数,注释掉第16行</span></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 128, 1)"> 1</span> test__0 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 0, 1
<span style="color: rgba(0, 128, 128, 1)"> 2</span> test__1 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 1, 2
<span style="color: rgba(0, 128, 128, 1)"> 3</span> test__2 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 2, 3
<span style="color: rgba(0, 128, 128, 1)"> 4</span> test__3 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 3, 4
<span style="color: rgba(0, 128, 128, 1)"> 5</span> <span style="color: rgba(0, 0, 0, 1)">finished
</span><span style="color: rgba(0, 128, 128, 1)"> 6</span> <span style="color: rgba(0, 0, 0, 1)">finished
</span><span style="color: rgba(0, 128, 128, 1)"> 7</span> <span style="color: rgba(0, 0, 0, 1)">finished
</span><span style="color: rgba(0, 128, 128, 1)"> 8</span> test__1 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 4, 5
<span style="color: rgba(0, 128, 128, 1)"> 9</span> test__0 threading <span style="color: rgba(0, 0, 255, 1)">is</span> printed 5, 6
<span style="color: rgba(0, 128, 128, 1)">10</span> finished</pre>
</div>
<p> </p>
<p><span style="font-size: 15px">另外,由于线程池实现了上下文管理协议(Context Manage Protocol),因此,程序可以使用 with 语句来管理线程池,这样即可避免手动关闭线程池,如上面的程序所示。</span><br><br><span style="font-size: 15px">此外,Exectuor 还提供了一个 <code>map(func, *iterables, timeout=None, chunksize=1)</code> 方法,该方法的功能类似于全局函数 map(),区别在于线程池的 map() 方法会为 iterables 的每个元素启动一个线程,以并发方式来执行 func 函数。这种方式相当于启动 len(iterables) 个线程,井收集每个线程的执行结果。</span><br><br><span style="font-size: 15px">例如,如下程序使用 Executor 的 map() 方法来启动线程,并收集线程任务的返回值:</span></p>
<p><span style="font-size: 15px">示例换成多参数的:</span></p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">def</span> test(value1, value2=<span style="color: rgba(0, 0, 0, 1)">None):
</span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">%s threading is printed %s, %s</span><span style="color: rgba(128, 0, 0, 1)">"</span>%<span style="color: rgba(0, 0, 0, 1)">(threading.current_thread().name, value1, value2))
</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> time.sleep(2)</span>
<span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(128, 0, 128, 1)">__name__</span> == <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__main__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">:
</span><span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> numpy as np
</span><span style="color: rgba(0, 0, 255, 1)">from</span> concurrent.futures <span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> ThreadPoolExecutor
threadPool </span>= ThreadPoolExecutor(max_workers=4, thread_name_prefix=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">test_</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">for</span> i <span style="color: rgba(0, 0, 255, 1)">in</span> range(0,10<span style="color: rgba(0, 0, 0, 1)">):
</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> test(str(i), str(i+1))</span>
threadPool.map(test, ,) # 这是运行一次test的参数,众所周知map可以让test执行多次,即一个[]代表一个参数,一个参数赋予不同的值即增加[]的长度如从到
threadPool.shutdown(wait</span>=True)</pre>
</div>
<p> </p>
<p><span style="font-size: 15px">
上面程序使用 map() 方法来启动 4个线程(该程序的线程池包含 4 个线程,如果继续使用只包含两个线程的线程池,此时将有一个任务处于等待状态,必须等其中一个任务完成,线程空闲出来才会获得执行的机会),map() 方法的返回值将会收集每个线程任务的返回结果。</span><br><span style="font-size: 15px">通过上面程序可以看出,使用 map() 方法来启动线程,并收集线程的执行结果,不仅具有代码简单的优点,而且虽然程序会以并发方式来执行 test() 函数,但最后收集的 test() 函数的执行结果,依然与传入参数的结果保持一致。</span></p>
<p> </p>
<p><span style="font-size: 15px">编写这个文档主要是因为示例文档没有多参数的。网上很多资料都是基于threadpool方法传参见</span></p>
<p><span style="font-size: 15px">Reference:</span></p>
<p><span style="font-size: 15px"> http://c.biancheng.net/view/2627.html</span></p>
<p><span style="font-size: 15px"> https://www.cnblogs.com/gongxijun/p/6862333.html</span></p><br><br>
来源:https://www.cnblogs.com/hoojjack/p/10846010.html
頁:
[1]