V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Morriaty
V2EX  ›  Python

进程池 ProcessPoolExecutor 如果一直不释放,会有什么弊端?

  •  
  •   Morriaty · 2018-08-29 16:56:16 +08:00 · 4512 次点击
    这是一个创建于 2039 天前的主题,其中的信息可能已经有所发展或是发生改变。

    场景是使用 tornado 写了一个服务,涉及到一些耗 cpu 的计算,使用了concurrent.futures.ProcessPoolExecutor

    那么最佳实践应该是每次请求时初始化一个进程池,还是保持一个全局的进程池?

    class MyHandler(BaseHandler):
        @coroutine
        def post(self, *args, **kwargs):
            ...
            with ProcessPoolExecutor() as process_pool:
                fs = [process_pool.submit(job) for job in jobs]
            ...
    

    还是这样?

    class MyHandler(BaseHandler):
        process_pool = ProcessPoolExecutor()
    
        @coroutine
        def post(self, *args, **kwargs):
            ...
            fs = [self.process_pool.submit(job) for job in jobs]
            ...
    
    4 条回复    2018-08-29 20:18:04 +08:00
    sujin190
        1
    sujin190  
       2018-08-29 17:45:44 +08:00
    一般来说每个 ProcessPoolExecutor 默认都会创建和 cpu 核心数相同的进程来执行所有任务,如果你想复用这个进程而不是每次都创建,那么就应该用全局的

    其实每次创建进程的开销应该还是挺大的,而且进程启动时在第一次添加任务的时候,所有一个全局进程持也没什么影响
    ipwx
        2
    ipwx  
       2018-08-29 20:08:27 +08:00
    应该用全局的
    kunluanbudang
        3
    kunluanbudang  
       2018-08-29 20:16:11 +08:00
    ProcessPool 应该全局共享
    codingKingKong
        4
    codingKingKong  
       2018-08-29 20:18:04 +08:00
    全局的, 不过我是 java... 线程池的实现里会有空闲时保持少量线程, 忙时再创建的特性, 以减少闲时资源占用.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5240 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 09:16 · PVG 17:16 · LAX 02:16 · JFK 05:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.