test_process_pool.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # coding:utf-8
  2. # 阻塞
  3. # from multiprocessing import Pool
  4. # def test(i):
  5. # print(i)
  6. # if __name__ == "__main__":
  7. # lists = range(100)
  8. # pool = Pool(8)
  9. # pool.map(test, lists)
  10. # pool.close()
  11. # pool.join()
  12. # 非阻塞
  13. from multiprocessing import Pool
  14. def test(i):
  15. print(i)
  16. if __name__ == "__main__":
  17. pool = Pool(8)
  18. for i in range(100):
  19. '''
  20. For循环中执行步骤:
  21. (1)循环遍历,将100个子进程添加到进程池(相对父进程会阻塞)
  22. (2)每次执行8个子进程,等一个子进程执行完后,立马启动新的子进程。(相对父进程不阻塞)
  23. apply_async为异步进程池写法。异步指的是启动子进程的过程,与父进程本身的执行(print)是异步的,而For循环中往进程池添加子进程的过程,与父进程本身的执行却是同步的。
  24. '''
  25. pool.apply_async(test, args=(i,)) # 维持执行的进程总数为8,当一个进程执行完后启动一个新进程.
  26. print("test")
  27. pool.close()
  28. pool.join()