创建进程池
from multiprocessing import Pool
import time,os
result = [] # 存放所有worker函数的返回值
def worker(msg):
time.sleep(1)
print "子进程的pid=%d,msg=%s" % (os.getpid(), msg)
return msg + " over"
# 创建进程池,3表示进程池中进程数量,即最多有3个进程一起执行。可以这样写:pool = Pool(3)
pool = Pool(processes=3)
for i in range(10): # 放入事件,有10个任务要向进程池中添加
msg = "hello %d" % i
# res = pool.apply(worker, (msg,)) # 堵塞的方式,一次只能添加1个任务
res = pool.apply_async(worker, (msg,)) # 一次能添加10个任务,但是仍然只有3个进程在同时执行
result.append(res) # 加入apply_async的返回值对象,该对象可以获取worker函数的返回结果
# 通过apply_async()的返回对象的get()方法获取返回值
for res in result:
print res.get()
pool.close() # 关闭进程池,不能再加入事件。相当于不能够再次添加新任务了
pool.join() # 阻塞等待回收