第五节 进程池

 1 from multiprocessing.pool import Pool
 2 import os, time, random
 3 
 4 def worker(msg):
 5     t_start = time.time()
 6     print('%s开始执行,进程号为%d' % (msg, os.getpid()))
 7     time.sleep(random.random()*2)
 8     t_stop = time.time()
 9     print(msg, '执行完毕, 耗时%.02f' % (t_stop-t_start))
10 
11 if __name__ == '__main__':
12     po = Pool()
13     for i in range(4):
14         # po.apply_async(要调用的函数, (传递给目标参数的元组))
15         # 这里虽然创建了10进程,但是只有3个会执行
16         po.apply_async(worker, (i,))
17     print('......start..........')
18     po.close()  # 关闭进程池,关闭后po不再接受新的请求
19     po.join()  # 等待po中所有子进程执行完成。必须放在close语句之后,等于阻塞作用,不然主进程会比子进程先结束
20     print('..........end..........')

猜你喜欢

转载自www.cnblogs.com/kogmaw/p/12575471.html