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 + 1)
end = time.time()
print("task %s runs %0.2f s"%(name,(end-start)))
if __name__ == "__main__":
print("parent process %s" %os.getpid())
p = Pool(4)
for i in range(8):
p.apply_async(long_time_task,args=(i,))
print("wait for all subprocess done...")
p.close()
p.join()
print("all subprocesses done.")
parent process 8988
wait for all subprocess done...
run task 0(8348)
run task 1(3124)
run task 2(8940)
run task 3(7088)
task 1 runs 1.15 s
run task 4(3124)
task 0 runs 1.34 s
run task 5(8348)
task 2 runs 2.73 s
run task 6(8940)
task 3 runs 2.73 s
run task 7(7088)
task 5 runs 1.92 s
task 6 runs 2.22 s
task 4 runs 3.89 s
task 7 runs 3.77 s
all subprocesses done.
代码很简单,每个任务打印出自己的pid号,然后随机延时一段时间。
进程池、线程池技术很重要,立个flag在这里,等自己来填。