等待一个子进程
使用场景:父进程在某个阶段等待子进程
# join方法
from multiprocessing import Process
import time, os
def task():
print('%s is running,parent id is <%s>' % (os.getpid(), os.getppid()))
time.sleep(3)
print('%s is done,parent id is <%s>' % (os.getpid(), os.getppid()))
if __name__ == '__main__':
p = Process(target=task, )
p.start()
p.join()
print('主', os.getpid(), os.getppid())
print(p.pid)
等待多个子进程
from multiprocessing import Process
import time, os
def task(name, n):
print('%s is running' % name)
time.sleep(n)
if __name__ == '__main__':
start = time.time()
p1 = Process(target=task, args=('子进程1', 5))
p2 = Process(target=task, args=('子进程2', 3))
p3 = Process(target=task, args=('子进程3', 2))
p_l = [p1, p2, p3]
for p in p_l:
p.start()
for p in p_l:
p.join()
print('主', (time.time() - start))