concurrent.futures
concurrent.futures
模块提供异步执行回调高层接口。注意 : 适合直接运行大量任务,不适合细节控制的任务。
基础的执行器
下面的多进程 和 多线程 接口 都是 基于 执行器对象的。(可继承,不能直接用)
class concurrent.futures.Executor
submit(fn,*args,**kwargs)
map(func , *iterables, timeout=None, chunksize=1)
shutdown( wair=True)
用法
多进程 和 多线程的 方法完全通用。
如果想从多线程修改为 多进程,只要 ThreadPoolExecutor --> ProcessPoolExecutor 换名即可。
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
import time, os
cpus = os.cpu_count()
thread_max_workers = cpus * 30
process_max_workers = cpus * 6
def ff(x):
time.sleep(1)
return x * 2 / (x + 1)
def method1():
with ThreadPoolExecutor(max_workers=30) as executor:
tasks = [executor.submit(ff, num) for num in range(2, 20)]
res = [task.result() for task in as_completed(tasks)]
print(len(res))
def method2():
with ThreadPoolExecutor(max_workers=30) as executor:
res = executor.map(ff, range(2, 22))
print(list(res))
if __name__ == '__main__':
method2()