python中的进程池和线程池

Python标准模块-concurrent.futures

#1 介绍
concurrent.futures模块提供了高度封装的异步调用接口
ThreadPoolExecutor:线程池,提供异步调用
ProcessPoolExecutor: 进程池,提供异步调用
Both implement the same interface, which is defined by the abstract Executor class.

#2 基本方法
#submit(fn, *args, **kwargs)
异步提交任务

#map(func, *iterables, timeout=None, chunksize=1) 
取代for循环submit的操作

#shutdown(wait=True) 
相当于进程池的pool.close()+pool.join()操作
wait=True,等待池内所有任务执行完毕回收完资源后才继续
wait=False,立即返回,并不会等待池内的任务执行完毕
但不管wait参数为何值,整个程序都会等到所有任务执行完毕
submit和map必须在shutdown之前

#result(timeout=None)
取得结果

#add_done_callback(fn)
回调函数

使用方法示例

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

import requests

# 给线程池设置最大工作的线程数
pool = ThreadPoolExecutor(10)
urls = [
    'http://cms-bucket.nosdn.127.net/2018/10/16/10e36050547445f6b8972daf7373a22'
    '2.jpeg',
    'http://kwcdn.000dn.com/swfs/59/39972xmyj0206/pm.jpg',
    'http://pic-bucket.nosdn.127.net/photo/0008/2018-10-14/DU48KHUS2FKJ0008NOS'
    '.jpg',
    'http://cms-bucket.nosdn.127.net/2018/10/16/b3a3fab2d65a41b79e0764727ae6d17'
    '9.jpeg',
    'http://cms-bucket.nosdn.127.net/2018/10/15/92cbe61fc5ec40ab94f5d2f0ed86771'
    '8.jpeg',
]


def task(url):
    response = requests.get(url)
    return response


# response会传递到call_back的参数中
def call_back(response):
    # 拿到的是一个future的对象
    # 从对象中取出task中返回的结果
    response.result()
    # 对回调过来的信息进行解析
    pass


for url in urls:
    # 使用回调函数能够用返回的结果实时的去解析, 实现异步非阻塞
    pool.submit(task, url).add_done_callback(call_back)

# 如果使用shutdown会等待所有任务执行结束后再去执行主线程中的代码
# pool.shutdown(True)
原文地址:https://www.cnblogs.com/louyifei0824/p/9864944.html