[关闭]
@JunQiu 2018-11-27T16:48:13.000000Z 字数 1820 阅读 1101

Python 多进程

language_py summary_2018/11


1、多进程

  1. import os
  2. pid = os.fork()
  3. if pid == 0:
  4. print(f"this is child process pid:{os.getpid()},father pid:{os.getppid()}")
  5. else:
  6. print(f"this is father pid:{os.getpid()}")
  7. // 输出
  8. this is father pid:10492
  9. this is child process pid:10493,father pid:10492

2、创建进程(multiprocessing)

  1. // 使用multiprocessing创建进程
  2. from multiprocessing import Process
  3. import os
  4. def child_process(name):
  5. print('Run child process %s (%s)...' % (name, os.getpid()))
  6. if __name__ == '__main__':
  7. p = Process(target=child_process, args=('name',))
  8. p.start()
  9. # 用于进程同步,不然不会等待子进程完成
  10. p.join()
  11. print('test async')
  12. // 输出
  13. Run child process name (10597)...
  14. test async
  15. // pool
  16. from multiprocessing import Pool
  17. import os
  18. import time
  19. def child_process(name):
  20. time.sleep(2)
  21. print('Run child process %s (%s)...' % (name, os.getpid()))
  22. if __name__ == '__main__':
  23. pool = Pool(5)
  24. for x in range(5):
  25. # 异步非阻塞 apply(阻塞)
  26. pool.apply(child_process, args=(x,))
  27. # pool.apply_async(child_process, args=(x,))
  28. pool.close()
  29. pool.join()
  30. print('test')
  31. // 输出
  32. Run child process 0 (10794)...
  33. Run child process 1 (10795)...
  34. Run child process 2 (10796)...
  35. Run child process 3 (10797)...
  36. Run child process 4 (10798)...
  37. test

3、进程同步

4、进程间通信

  1. // queue
  2. from multiprocessing import Process, Queue
  3. import os
  4. import time
  5. # 写进程
  6. def child_process_write(q):
  7. i = 0
  8. while True:
  9. time.sleep(2)
  10. print(f"write {i}")
  11. q.put(i)
  12. i += 1
  13. # 读进程
  14. def child_process_read(q):
  15. while True:
  16. time.sleep(2)
  17. print(f"get {q.get(True)}")
  18. if __name__ == '__main__':
  19. q = Queue()
  20. pw = Process(target=child_process_write, args=(q,))
  21. pw.start()
  22. pr = Process(target=child_process_read, args=(q,))
  23. pr.start()
  24. // 输出
  25. write 0
  26. get 0
  27. write 1
  28. get 1
  29. write 2
  30. get 2

5、参考

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注