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