Python标准库为我们提供了threading(多线程模块)和multiprocessing(多进程模块)。从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了 ThreadPoolExecutor 和 ProcessPoolExecutor 两个类,实现了对threading和multiprocessing的更高级的抽象,对编写线程池/进程池提供了直接的支持。

Executor是一个抽象类,它不能被直接使用。但是它提供的两个子类ThreadPoolExecutor和ProcessPoolExecutor却是非常有用,顾名思义两者分别被用来创建线程池和进程池的代码。

核心原理是:concurrent.futures会以子进程的形式,平行的运行多个python解释器,从而令python程序可以利用多核CPU来提升执行速度。由于子进程与主解释器相分离,所以他们的全局解释器锁也是相互独立的。每个子进程都能够完整的使用一个CPU内核,可以利用multiprocessing实现真正的并行计算。


最大公约数案例:

 from concurrent.futures.process import ProcessPoolExecutor
from concurrent.futures.thread import ThreadPoolExecutor import time def program_timer(func):
def inner(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'{func.__name__}共耗时{end-start}')
return result
return inner def gcd(pair):
a, b = pair
low = min(a, b)
for i in range(low, 0, -1):
if a % i == 0 and b % i == 0:
return i numbers = [
(1963309, 2265973), (1879675, 2493670), (2030677, 3814172),
(1551645, 2229620), (1988912, 4736670), (2198964, 7876293)
] @program_timer
def _main1(): # 普通执行
for i in numbers:
gcd(i) @program_timer
def _main2(): # 多线程
pool = ThreadPoolExecutor(max_workers=2)
pool.map(gcd, numbers) @program_timer
def _main3(): # 多进程
pool = ProcessPoolExecutor(max_workers=2)
pool.map(gcd, numbers) if __name__ == '__main__':
_main1()
_main2()
_main3()

执行结果:

_main1共耗时0.7035946846008301
_main2共耗时0.030988216400146484
_main3共耗时0.42536211013793945

最新文章

  1. JS魔法堂:再识ASCII实体、符号实体和字符实体
  2. html+css+javascript实现列表循环滚动示例代码
  3. xubuntu12.04配置
  4. 无法远程访问虚拟机中的EM (Oracle Enterprise Manager)
  5. android BitmapFacty.Options的用法
  6. 初识phaser框架——开源的HTML5 2D游戏开发框架
  7. memcached采用的网络模型
  8. Javascript进阶篇——(DOM—节点---属性、访问节点)—笔记整理
  9. MYSQL分页存储过程及事务处理--转自peace
  10. CairoSVG - Convert SVG to PNG or PDF - Contents
  11. sql数据库删除表的外键约束(INSERT 语句与 FOREIGN KEY 约束"XXX"冲突。该冲突发生于数据库"XXX",表"XXX", column 'XXX)
  12. Visual Studio中的TabControl控件的用法
  13. [js高手之路]设计模式系列课程-发布者,订阅者重构购物车
  14. Shell脚本——特殊符号
  15. MySql 创建新用户
  16. MPP数据库
  17. Java -- JDBC 学习--PreparedStatement
  18. 多目标遗传算法 ------ NSGA-II (部分源码解析) 实数、二进制编码的变异操作 mutation.c
  19. linux基础(2)-基础命令和基础特性
  20. 2018-2019-2 网络对抗技术 20165324 Exp3:免杀原理与实践

热门文章

  1. Confluence 6 计划任务
  2. Java测试代码(很不完整,建议大家别看,过几天会再发一次难的版本)
  3. day07 元组类型 字典类型 集合
  4. Best Cow Line(POJ3617)
  5. java URI
  6. Practical Web Penettation Testing (the first one Mutillidae 大黄蜂)
  7. Git使用三:git的使用流程
  8. 解决:sudo: pip: command not found
  9. Windows Internals 笔记——线程局部存储区
  10. 处理Task引发的异常