1. 3种方式比较
# fork 父子进程都执行任务 抛弃使用
ret = os.fork()
if ret == 0:
#子进程
else:
#父进程
#父进程会等待子进程结束
#主进程,子进程都执行
p1 = Process(target=xxx)
p1.start()
#主进程一般用来等待(join)。。。真正的任务都做子进程中执行
pool = Pool(30)
pool.apply_async(xxxx)
pool.join()
2.apply堵塞式 不用
from multiprocessing import Pool
import os
import random
import time
def worker(num):
for i in range(5):
print("===pid=%d==num=%d="%(os.getpid(), num))
time.sleep(1)
#3表示 进程池中对多有3个进程一起执行
pool = Pool(3)
for i in range(10):
print("---%d---"%i)
pool.apply(worker, (i,)) #堵塞式的方式
pool.close()
pool.join()
---0---
===pid=3197==num=0=
===pid=3197==num=0=
===pid=3197==num=0=
===pid=3197==num=0=
===pid=3197==num=0=
---1---
===pid=3198==num=1=
===pid=3198==num=1=
===pid=3198==num=1=
===pid=3198==num=1=
===pid=3198==num=1=
---2---
===pid=3199==num=2=
===pid=3199==num=2=
===pid=3199==num=2=
===pid=3199==num=2=
===pid=3199==num=2=
---3---
===pid=3197==num=3=
===pid=3197==num=3=
===pid=3197==num=3=
===pid=3197==num=3=