Morriaty
V2EX  ›  Python

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

By Morriaty at 2018 年 8 月 29 日 · 5545 次点击

场景是使用 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 年 8 月 29 日
一般来说每个 ProcessPoolExecutor 默认都会创建和 cpu 核心数相同的进程来执行所有任务,如果你想复用这个进程而不是每次都创建,那么就应该用全局的

其实每次创建进程的开销应该还是挺大的,而且进程启动时在第一次添加任务的时候,所有一个全局进程持也没什么影响
ipwx
   2
ipwx  
   2018 年 8 月 29 日
应该用全局的
kunluanbudang
   3
kunluanbudang  
   2018 年 8 月 29 日
ProcessPool 应该全局共享
codingKingKong
   4
codingKingKong  
   2018 年 8 月 29 日
全局的, 不过我是 java... 线程池的实现里会有空闲时保持少量线程, 忙时再创建的特性, 以减少闲时资源占用.
推荐学习书目
› 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
© 2026 V2EX · 38ms · 3.9.8.5