等待一个子进程

使用场景:父进程在某个阶段等待子进程

  1. # join方法
  2. from multiprocessing import Process
  3. import time, os
  4. def task():
  5. print('%s is running,parent id is <%s>' % (os.getpid(), os.getppid()))
  6. time.sleep(3)
  7. print('%s is done,parent id is <%s>' % (os.getpid(), os.getppid()))
  8. if __name__ == '__main__':
  9. p = Process(target=task, )
  10. p.start()
  11. p.join()
  12. print('主', os.getpid(), os.getppid())
  13. print(p.pid)

进程阻塞.gif

等待多个子进程

  1. from multiprocessing import Process
  2. import time, os
  3. def task(name, n):
  4. print('%s is running' % name)
  5. time.sleep(n)
  6. if __name__ == '__main__':
  7. start = time.time()
  8. p1 = Process(target=task, args=('子进程1', 5))
  9. p2 = Process(target=task, args=('子进程2', 3))
  10. p3 = Process(target=task, args=('子进程3', 2))
  11. p_l = [p1, p2, p3]
  12. for p in p_l:
  13. p.start()
  14. for p in p_l:
  15. p.join()
  16. print('主', (time.time() - start))

进程阻塞.gif