Pool模块
Pool模块:from multiprocessing import Pool
创建进程池对象:p=Pool(n),n为允许同时执行的最大进程数
进程开启:p.apply(work,args=(i,)),work为调用的函数,args传递参数;非阻塞执行为p.apply_async(func [, args [, kwargs]])
p.join()控制主进程在子进程结束后继续进行
示例代码
import os,time<br>from multiprocessing import Pool<br><br>def work(n):<br> print('%s run' %os.getpid())<br> time.sleep(3)<br> return n**2<br><br>if __name__ == '__main__':<br> p=Pool(3) #进程池中从无到有创建三个进程,以后一直是这三个进程在执行任务<br> res_l=[]<br> for i in range(10):<br> res=p.apply(work,args=(i,)) # 同步调用,直到本次任务执行完毕拿到res,等待任务work执行的过程中可能有阻塞也可能没有阻塞<br> # 但不管该任务是否存在阻塞,同步调用都会在原地等着<br> print(res_l)
ProcessPoolExecutor
ProcessPoolExecutor模块:from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
创建对象:executor=ProcessPoolExecutor(max_workers=3)
开启进程(异步):future=executor.submit(task,i)
关闭进程:executor.shutdown(True)
获取进程结果:future.result()
回调函数:add_done_callback(fn)
map简化:executor.map(task,range(1,12))
对等于:<br># for i in range(11):<br> # future=executor.submit(task,i)