V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Aug 29, 2018 · 5181 views
    This topic created in 2807 days ago, the information mentioned may be changed or developed.

    场景是使用 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 replies    2018-08-29 20:18:04 +08:00
    sujin190
        1
    sujin190  
       Aug 29, 2018
    一般来说每个 ProcessPoolExecutor 默认都会创建和 cpu 核心数相同的进程来执行所有任务,如果你想复用这个进程而不是每次都创建,那么就应该用全局的

    其实每次创建进程的开销应该还是挺大的,而且进程启动时在第一次添加任务的时候,所有一个全局进程持也没什么影响
    ipwx
        2
    ipwx  
       Aug 29, 2018
    应该用全局的
    kunluanbudang
        3
    kunluanbudang  
       Aug 29, 2018
    ProcessPool 应该全局共享
    codingKingKong
        4
    codingKingKong  
       Aug 29, 2018
    全局的, 不过我是 java... 线程池的实现里会有空闲时保持少量线程, 忙时再创建的特性, 以减少闲时资源占用.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4740 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 04:07 · PVG 12:07 · LAX 21:07 · JFK 00:07
    ♥ Do have faith in what you're doing.