Python Multiprocessing Pool 核心方法与参数详解

陈默
陈默
发布时间:2026-10-13 | 2人浏览过
原创

本文深入解析Python multiprocessing模块中Pool类的核心方法。详细讲解star()启动进程、join()同步等待、close()防止阻塞的作用机制,并说明target、args等关键参数的配置方式。通过实际代码示例展示多进程并发执行过程及输出结果,帮助开发者掌握进程池的正确使用技巧。

Multiprocessing Pool 核心方法解析

首先介绍以下几个关键方法:

  • star() 用于启动进程,
  • join() 实现进程间的同步,确保主进程等待所有子进程执行完毕。
  • close() 用于阻止向进程池 Pool 提交新任务,从而避免造成进程阻塞。

关键参数配置说明

相关参数说明:

target 指定要调用的函数名称。

args 为函数所需的参数,以元组(tuple)形式传入。

代码示例与执行结果分析

具体用法如下:

multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

编写一个示例代码:


from multiprocessing import Pool
import os,time


def pr(str):
  print("The " + str + " is %s" %(os.getpid()))
  time.sleep(1)
  print("The " + str + " is close")


if __name__ == "__main__":

  print('-------------------------------')
  print("the current pid: "+ str(os.getpid()))
  # 默认为自己电脑的核数
  p = Pool(2)
  for i in range(5):
    p.apply_async(pr,args=('xdxd',))
  p.close()
  p.join()
  print("----------close-----------------")

从运行结果可以看出,系统启动了2个进程同时执行。并发进程的数量取决于Pool中设置的最大进程数以及计算机的物理核心数。

程序输出结果如下:


-------------------------------
the current pid: 9562
The xdxd is 9563
The xdxd is 9564
The xdxd is close
The xdxd is close
The xdxd is 9563
The xdxd is 9564
The xdxd is close
The xdxd is close
The xdxd is 9563
The xdxd is close
----------close-----------------

以上内容为本文的全部总结,希望对各位的学习有所帮助,也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表