from multiprocessing import Pool
import os, time, random
def worker(msg):
t_start = time.time()
print('{}开始执行,进程号为 {}'.format(msg, os.getpid()))
# random.random() #随机生成0-1之间的浮点数
time.sleep(random.random() * 2)
t_stop = time.time()
print('{} 执行完毕,耗时{}'.format(msg, t_stop - t_start))
def main():
po = Pool(3)
for i in range(10):
# Pool.apply_async(强调要用的目标, (传递参数,))
po.apply_async(worker, (i,))
print('---开始---')
po.close() # 关闭进程池,关闭后po不再接受新的请求
po.join() # 等待po中所有进程执行完成,必须放在close语句之后
print('---结束---')
if __name__ == '__main__':
main()