抨击线程的往往是系统程序员,他们考虑的使用场景对一般的应用程序员来说,也许一生都不会遇到……应用程序员遇到的使用场景,99% 的情况下只需知道如何派生一堆独立的线程,然后用队列收集结果。1
——Michele Simionato
深度思考 Python 的人
1摘自 Michele Simionato 发表的文章“Threads, processes and concurrency in Python: some thoughts”(http://www.artima.com/weblogs/viewpost.jsp?thread=299551),副标题为“Removing the hype around the multicore (non) revolution and some (hopefully) sensible comment about threads and other forms of concurrency”。
本章主要讨论 Python 3.2 引入的 concurrent.futures 模块,从 PyPI 中安装 futures 包(https://pypi.python.org/pypi/futures/)之后,也能在 Python 2.5 及以上版本中使用这个库。这个库封装了前面的引文中 Michele Simionato 所述的模式,特别易于使用。
这一章还会介绍“期物”(future)2 的概念。期物指一种对象,表示异步执行的操作。这个概念的作用很大,是 concurrent.futures 模块和 asyncio 包(第 18 章讨论)的基础。
2“期物”是我自创的词,其中的“物”是指“物件”(object,也就是对象)。起初读者可能不明其意,可与期货、期权和期房对比理解。——译者注
下面举个示例,作为引子。