Python中进行并发编程一般使用threading和multiprocessing模块,不过大部分的并发编程任务都是派生一系列线程/进程,从队列中收集资源,然后用队列收集结果。在这些任务中,往往需要生成线程池,concurrent.futures模块对threading和multiprocessing模块进行了进一步的包装,可以很方便地实现池的功能。
安装
python3中concurrent.futures是标准库,在python2中还需要自己安装concurrent.futures。
Executor与Future
concurrent.futures供了ThreadPoolExecutor和ProcessPoolExecutor两个类,都继承自Executor,分别被用来创建线程池和进程池,接受max_workers参数,代表创建的线程数或者进程数。ProcessPoolExecutor的max_workers参数可以为空,程序会自动创建基于电脑cpu数目的进程数。
1 2 3 4 5 6 7 8 9 |
|
submit()方法只能进行单个任务,用并发多个任务,需要使用map与as_completed。
map
1 2 3 4 5 6 7 8 |
|