# -*- coding:utf-8 -*-
from multiprocessing import Pool
import os, time, random
def long_time_task(name): #执行函数
print('run task %s (%s)...'% (name,os.getpid()))
start = time.time()
time.sleep(random.random()*3) #random()生成0-1之间的随即实数
end = time.time()
print('task %s run %0.2f seconds.'% (name,end-start))
if __name__ =='__main__':
print('parents process %s.'% os.getpid())
p = Pool(4) #意为设定同时进行的子进程数,在一个进程池内,根据cpu核数进行的.
for i in range(8): #为8个进程提供name 0,1,2,3,4,5,6,7
p.apply_async(long_time_task, args = (i,)) #apply_async()方法下面说明
print('waiting for all subprocesses done...')
p.close() #关闭进程池,不在接收新的任务
p.join()
print('all subprocesses done')
#apply_async(func[,args[,kwds[,callback = None]]]) #非阻塞且支持结果返回进行回调
#apply_async(函数,不定参数) #四个进程在Pool进程池内并行(分给4核cpu),剩下的交替进行.