# coding:utf-8 import os import time from multiprocessing import Pool def func(n): print("%s:%s" % (os.getpid(), n)) return n**2 def func2(n): print("%s:%s" % (os.getpid(), n)) time.sleep(1) return n**2 if __name__ == '__main__': start_time = time.time() pool = Pool(5) # 进程池中从无到有创建5个进程,以后一直是这5个进程在执行任务 res_lst = [] for i in range(10): res = pool.apply_async(func, args=(i,)) # 异步运行,根据进程池中有的进程数,每次最多3个子进程在异步执行,并且可以执行不同的任务,传送任意的参数了。 # 返回结果之后,将结果放入列表,归还进程,之后再执行新的任务 # 需要注意的是,进程池中的三个进程不会同时开启或者同时结束 # 而是执行完一个就释放一个进程,这个进程就去接收新的任务。 res_lst.append(res) # 异步apply_async用法:如果使用异步提交的任务,主进程需要使用join,等待进程池内任务都处理完,然后可以用get收集结果 # 否则,主进程结束,进程池可能还没来得及执行,也就跟着一起结束了 pool.close() # 不是关闭进程池,而是结束进程池接收任务,确保没有新任务再提交过来。 pool.join() # 感知进程池中的任务已经执行结束,只有当没有新的任务添加进来的时候,才能感知到任务结束了,所以在join之前必须加上close方法 print([r.get() for r in res_lst]) # 使用get来获取apply_aync的结果,如果是apply,则没有get方法,因为apply是同步执行,立刻获取结果,也根本无需get print("无阻塞程序的执行时间:", time.time() - start_time) s_time = time.time() pool2 = Pool(5) # 进程池中从无到有创建5个进程,以后一直是这5个进程在执行任务 res_lst = [] for i in range(10): res = pool2.apply_async(func2, args=(i,)) res_lst.append(res) pool2.close() pool2.join() print([r.get() for r in res_lst]) print("有阻塞程序的执行时间:", time.time() - s_time) # 8860:0 # 8860:1 # 8860:2 # 8860:3 # 8860:4 # 8860:5 # 8860:6 # 8860:7 # 8860:8 # 8860:9 # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # 无阻塞程序的执行时间: 0.609375 # 7728:0 # 3668:1 # 7288:2 # 8300:3 # 10168:4 # 7728:5 # 3668:6 # 7288:7 # 8300:8 # 10168:9 # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # 有阻塞程序的执行时间: 2.625