热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Python子进程与子进程池的应用

Python的多线程受到GIL(GlobalInterpreterLock)的限制,GIL是一把加到了Python的解释器的锁,使得在任意时刻只允许一个

    Python 的多线程受到 GIL(Global Interpreter Lock) 的限制,GIL 是一把加到了 Python 的解释器的锁,使得在任意时刻只允许一个 Python 进程使用 Python 解释器,也就是任意时刻,Python 只有一个线程在运行。

    GIL 严重影响了计算密集型(CPU-bound) 的多线程程序,此时的多线程与单线程性能没什么差异,也发挥不了多核的威力。但对 I/O 密集型(I/O-bound) 影响不大,因为 CPU 多数时候是在等待。

    为了突破 GIL 的 CPU 密集型程序的限制,可以使用非 CPython 解释器,如 Jython, IronPython 或 PyPy, 更为现实的做法就是使用子进程来替代线程去承担较为繁重的计算任务,因为 GIL 是加在进程上的,所以新的进程有独立的 GIL.

新建子进程来处理任务

    需用到 multiprocessing.Process 类,这个类在 Python 2.6 就开始存在了。一般的编程语言创建一个进程是要去执行一个外部任命,然后获得它的输出,而 Python 可以像创建线程一样创建子进程,且欲执行的任务直接由 Python 在其中编写

from datetime import datetime
import time
from multiprocessing import Process
import osdef job(name):for _ in range(3):print('[Child {}][{}]'.format(os.getpid(), datetime.now()))time.sleep(1)print(f'sub process {os.getpid()} {name} done')if __name__ == '__main__':p = Process(target=job, args=('bob',)) # 留意如何向子进程传递参数p.start()print(f'main process {os.getpid()} done') # p.pid 可以得到子进程的 IDp.join() # 如果不 join 的话,主进程一退出,子进程也随即结束
from datetime import datetimeimport timefrom multiprocessing import Processimport osdef job ( name ) :for _ in range ( 3 ) :print ( '[Child {}][{}]' . format ( os . getpid ( ) , datetime . now ( ) ) )time . sleep ( 1 )print ( f 'sub process {os.getpid()} {name} done' )if __name__ == '__main__' :p = Process ( target = job , args = ( 'bob' , ) ) # 留意如何向子进程传递参数p . start ( )print ( f 'main process {os.getpid()} done' ) # p.pid 可以得到子进程的 IDp . join ( ) # 如果不 join 的话,主进程一退出,子进程也随即结束

执行后输出

main process 67474 done [Child][2021-09-02 19:32:14.121689] [Child][2021-09-02 19:32:15.126048] [Child][2021-09-02 19:32:16.129741] sub process 67476 bob done
可以看到主进程与子进程分别有自己不同的进程 ID。

    还有就是 if name == ‘main’ 变得是必要的语句了,不能把想要立即执行的代码丢在函数外了事,否则就是出现下面的错误信息

RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable.

    进程之间传递参数除了用 args=(‘bob’,) 的任务参数外,还可用 multiprocessing.Pipe 在进程之间双向通信。也可以通过内存来共享数据,用到 multiprocessing.Value 和 multiprocessing.Array 。这一部分的详细内容请参考官方文档,在实际编程中可能会经常用到。

    执行进程任务也可以加锁,用 multiprocessing.Lock , lock.acquire()…try: … finally: lock.release() 标准模式,因为进程之间需要保护对系统中唯一资源的竞争

在 Jupyter 中使用 Process 的问题

如果直接把上面的代码放到 JpyterLab 中去执行,将会看到这样的错误

Traceback (most recent call last):File "", line 1, in <module>File "/Users/yanbin/jupyterlab-venv/lib/python3.9/multiprocessing/spawn.py", line 116, in spawn_mainexitcode = _main(fd, parent_sentinel)File "/Users/yanbin/jupyterlab-venv/lib/python3.9/multiprocessing/spawn.py", line 126, in _mainself = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'job' on __main__' (built-in)>
Traceback ( most recent call last ) :File "" , line 1 , in & lt ; module & gt ;File "/Users/yanbin/jupyterlab-venv/lib/python3.9/multiprocessing/spawn.py" , line 116 , in spawn_mainexitcode = _main ( fd , parent_sentinel )File "/Users/yanbin/jupyterlab-venv/lib/python3.9/multiprocessing/spawn.py" , line 126 , in _mainself = reduction . pickle . load ( from_parent )AttributeError : Can '
t get attribute ' job ' on <module ' __main_ _ ' ( built - in ) & gt ;

    这不是 Python 版本的问题,放别的 Python 3.8 下也是这样的错误,原因就是 Jupyter 无法与 multiprocessing 一同工作,pickle 模块在序列化数据向进程发送时出异常。解决办法是要用 multiprocess 替换掉 multiprocessing 模块

pip install multiprocess from multiprocess import Process

然后在 JupyterLab 中执行替换成 multiprocess 的版本,输出略有不同

[Child][2021-09-02 19:41:55.326549] main process 62917 done [Child][2021-09-02 19:41:56.335774] [Child][2021-09-02 19:41:57.342169] sub process 68144 bob done

    与在 Python 终端执行的一个区别是,子进程总有一行在 main process … 之前输出,这没什么要紧的。

使用进程池

有线程池,相应的也有进程池,参照一个官方文档中的简单例子

from multiprocessing import Pool
import osdef f(x):print(f'subprocess id: {os.getpid()}')return x*xif __name__ == '__main__':with Pool(5) as p:print(p.map(f, [1, 2, 3]))
from multiprocessing import Poolimport osdef f ( x ) :print ( f 'subprocess id: {os.getpid()}' )return x* xif __name__ == '__main__' :with Pool ( 5 ) as p :print ( p . map ( f , [ 1 , 2 , 3 ] ) )

输出为

subprocess id: 69348 subprocess id: 69350 subprocess id: 69347 [1, 4, 9]

这是用到了 Context 来管理进程池,如果逐步操作就是

pool = Pool(5)
[pool.apply_async(f, args=(i, )) for i in (1, 2, 3)]
pool.close()
pool.join()
pool = Pool ( 5 )[ pool . apply_async ( f , args = ( i , ) ) for i in ( 1 , 2 , 3 ) ]pool . close ( )pool . join ( )

进程池执行器

    这个翻译有点别扭,直接叫 ProcessPoolExecutor 习惯些。
ProcessPoolExecutor 在 concurrent.futures 模块中,它是 Python 3.2 加入进来的。至于用法呢,只要想像它是 ThreadPoolExecutor 的进程版本就差不多了。它提供的方法用

  1. submit(fn, /, *args, **kwargs): 向进程池提交任务
  2. map(func, *iterables, timeout=None, chunksize=1): 批量提交任务的快捷写法
  3. shutdown(wait=True, *, cancel_futures=False): 关闭进程池

首先仍然用一个使用了 with 关键字的写法

from concurrent.futures import ProcessPoolExecutor
import osdef f(x):return f'{os.getpid()}: {x*x}'if __name__ == '__main__':with ProcessPoolExecutor(max_workers=5) as executor:results = executor.map(f, [1, 3, 4])for i in results:print(i)
from concurrent . futures import ProcessPoolExecutorimport osdef f ( x ) :return f '{os.getpid()}: {x*x}'if __name__ == '__main__' :with ProcessPoolExecutor ( max_workers = 5 ) as executor :results = executor . map ( f , [ 1 , 3 , 4 ] )for i in results :print ( i )

输出如下:

    也可以用 submit() 函数来提交任务,得到的是一个 Future。关于 Future, 以及类似的 submit(), executor.map() 函数在Python 多线程编程 有所覆盖。

    另外,在构建 ProcessPoolExecutor 时如果不指 max_workers 参数将会取系统 CPU 的内核数(multiprocessing.cpu_count())。

    如果不对 ProcessPoolExecutor 使用 with 语句,则需要去用 submit() 提交的任务进行 wait,参照

在这里插入图片描述

    如果对软件测试、接口测试、自动化测试、持续集成、面试经验。感兴趣可以进到806549072,群内会有不定期的分享测试资料。还会有技术大牛,业内同行一起交流技术


推荐阅读
  • MySQL索引详解与优化
    本文深入探讨了MySQL中的索引机制,包括索引的基本概念、优势与劣势、分类及其实现原理,并详细介绍了索引的使用场景和优化技巧。通过具体示例,帮助读者更好地理解和应用索引以提升数据库性能。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • 实体映射最强工具类:MapStruct真香 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • python的交互模式怎么输出名文汉字[python常见问题]
    在命令行模式下敲命令python,就看到类似如下的一堆文本输出,然后就进入到Python交互模式,它的提示符是>>>,此时我们可以使用print() ... [详细]
  • 本文详细介绍了如何在Ubuntu系统中下载适用于Intel处理器的64位版本,涵盖了不同Linux发行版对64位架构的不同命名方式,并提供了具体的下载链接和步骤。 ... [详细]
  • 基于KVM的SRIOV直通配置及性能测试
    SRIOV介绍、VF直通配置,以及包转发率性能测试小慢哥的原创文章,欢迎转载目录?1.SRIOV介绍?2.环境说明?3.开启SRIOV?4.生成VF?5.VF ... [详细]
  • 深入探讨CPU虚拟化与KVM内存管理
    本文详细介绍了现代服务器架构中的CPU虚拟化技术,包括SMP、NUMA和MPP三种多处理器结构,并深入探讨了KVM的内存虚拟化机制。通过对比不同架构的特点和应用场景,帮助读者理解如何选择最适合的架构以优化性能。 ... [详细]
  • 配置Windows操作系统以确保DAW(数字音频工作站)硬件和软件的高效运行可能是一个复杂且令人沮丧的过程。本文提供了一系列专业建议,帮助你优化Windows系统,确保录音和音频处理的流畅性。 ... [详细]
  • 探索电路与系统的起源与发展
    本文回顾了电路与系统的发展历程,从电的早期发现到现代电子器件的应用。文章不仅涵盖了基础理论和关键发明,还探讨了这一学科对计算机、人工智能及物联网等领域的深远影响。 ... [详细]
  • 本文详细介绍了Java库中com.vividsolutions.jts.io.WKTWriter类的appendGeometryCollectionText()方法,并提供了实际代码示例,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 在Java中,this是一个引用当前对象的关键字。如何通过this获取并显示其所指向的对象的属性和方法?本文详细解释了this的用法及其背后的原理。 ... [详细]
  • FinOps 与 Serverless 的结合:破解云成本难题
    本文探讨了如何通过 FinOps 实践优化 Serverless 应用的成本管理,提出了首个 Serverless 函数总成本估计模型,并分享了多种有效的成本优化策略。 ... [详细]
  • 在进行Revit插件开发时,经常会遇到窗口被其他应用程序遮挡的问题。本文将介绍如何通过简单的代码调整,确保插件窗口始终保持在Revit主界面的最前端,提升用户体验。 ... [详细]
author-avatar
书友395154
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有