Python 中的并发 - 线程池
假设我们必须为多线程任务创建大量线程。由于线程太多,可能会出现许多性能问题,因此计算成本最高。主要问题可能是吞吐量受限。我们可以通过创建线程池来解决这个问题。线程池可以定义为一组预先实例化的空闲线程,这些线程随时准备工作。当我们需要执行大量任务时,创建线程池比为每个任务实例化新线程更可取。线程池可以管理大量线程的并发执行,如下所示 −
如果线程池中的线程完成执行,则可以重用该线程。
如果线程终止,将创建另一个线程来替换该线程。
Python 模块 – Concurrent.futures
Python 标准库包含 concurrent.futures 模块。此模块是在 Python 3.2 中添加的,用于为开发人员提供启动异步任务的高级接口。它是 Python 线程和多处理模块顶层的抽象层,用于提供使用线程池或进程池运行任务的接口。
在后续章节中,我们将了解 concurrent.futures 模块的不同类。
Executor 类
Executor 是 Python 模块 concurrent.futures 的一个抽象类。它不能直接使用,我们需要使用以下具体子类之一 −
- ThreadPoolExecutor
- ProcessPoolExecutor
ThreadPoolExecutor – 一个具体子类
它是 Executor 类的一个具体子类。该子类使用多线程,我们得到一个线程池来提交任务。该池将任务分配给可用线程并安排它们运行。
如何创建 ThreadPoolExecutor?
借助 concurrent.futures 模块及其具体子类 Executor,我们可以轻松创建一个线程池。为此,我们需要构造一个 ThreadPoolExecutor,并指定池中所需的线程数。默认情况下,该数字为 5。然后我们可以向线程池提交任务。当我们 submit() 任务时,我们会返回一个 Future。Future 对象有一个名为 done() 的方法,它告知未来是否已解决。通过此方法,已为该特定未来对象设置了一个值。当任务完成时,线程池执行器会将该值设置为未来对象。
示例
from concurrent.futures import ThreadPoolExecutor from time import sleep def task(message): sleep(2) return message def main(): executor = ThreadPoolExecutor(5) future = executor.submit(task, ("Completed")) print(future.done()) sleep(2) print(future.done()) print(future.result()) if __name__ == '__main__': main()
输出
False True Completed
在上面的例子中,ThreadPoolExecutor 已构建为具有 5 个线程。然后,将等待 2 秒后才发出消息的任务提交给线程池执行器。从输出中可以看出,任务直到 2 秒才完成,因此对 done() 的第一次调用将返回 False。2 秒后,任务完成,我们通过调用其上的 result() 方法获得未来的结果。
实例化 ThreadPoolExecutor – 上下文管理器
实例化 ThreadPoolExecutor 的另一种方法是借助上下文管理器。它的工作原理与上面示例中使用的方法类似。使用上下文管理器的主要优点是它在语法上看起来不错。可以借助以下代码进行实例化 −
with ThreadPoolExecutor(max_workers = 5) as executor
示例
以下示例借用自 Python 文档。在此示例中,首先必须导入 concurrent.futures 模块。然后创建一个名为 load_url() 的函数,它将加载请求的 url。然后,该函数创建 ThreadPoolExecutor ,池中有 5 个线程。ThreadPoolExecutor 已被用作上下文管理器。我们可以通过调用其上的 result() 方法来获取 Future 的结果。
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/'] def load_url(url, timeout): with urllib.request.urlopen(url, timeout = timeout) as conn: return conn.read() with concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor: 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)))
输出
以下是上述 Python 脚本的输出 −
'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed> 'http://www.foxnews.com/' page is 229313 bytes 'http://www.cnn.com/' page is 168933 bytes 'http://www.bbc.co.uk/' page is 283893 bytes 'http://europe.wsj.com/' page is 938109 bytes
Executor.map() 函数的使用
Python map() 函数广泛应用于许多任务。其中一项任务是将某个函数应用于可迭代对象中的每个元素。类似地,我们可以将迭代器的所有元素映射到一个函数,并将它们作为独立作业提交给我们的 ThreadPoolExecutor。请考虑以下 Python 脚本示例,以了解该函数的工作原理。
示例
在下面的示例中,map 函数用于将 square() 函数应用于 values 数组中的每个值。
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import as_completed values = [2,3,4,5] def square(n): return n * n def main(): with ThreadPoolExecutor(max_workers = 3) as executor: results = executor.map(square, values) for result in results: print(result) if __name__ == '__main__': main()
输出
上述 Python 脚本生成以下输出 −
4 9 16 25