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

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

本文深入解析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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。