from multiprocessing import Pool import os import time def worker(num): print("task <%s> is runing <%d>" % (os.getpid(), num)) time.sleep(2) def main(): # 定义一个进程池,最大进程数3 po = Pool(3) for i in range(0, 10): # Pool().apply_async(要调用的目标,(传递给目标的参数元祖,)) # 每次循环将会用空闲出来的子进程去调用目标 po.apply_async(worker, args=(i,)) print("---start---") # 关闭进程池,关闭后po不再接收新的请求 po.close() # 等待po中所有子进程执行完毕,必须放在close语句之后 po.join() print("---end---") if __name__ == '__main__': main()