首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免使用tornado.ioloop.IOLoop.run_in_executor时线程过多?

如何避免使用tornado.ioloop.IOLoop.run_in_executor时线程过多?
EN

Stack Overflow用户
提问于 2019-08-29 09:25:15
回答 1查看 1.8K关注 0票数 2

我使用tornado.ioloop.IOLoop.run_in_executor将同步函数更改为异步函数,但是每次调用该函数时,都会创建一个线程,而不是终止线程。

下面是一个模拟可复制的示例(至少在我的机器上是可复制的):

代码语言:javascript
复制
#!/usr/bin/env python3                                                          

import time
import tornado.ioloop
import tornado.web

def slow_func():
    time.sleep(1)
    print('slow func returned')
    return 'succ\n'

class TestHandler(tornado.web.RequestHandler):
    async def get(self):
        print('GET called')
        try:
            result = await tornado.ioloop.IOLoop.current().run_in_executor(None, slow_func)
        except Exception as e:
            print(e)
        self.write(result)
        print('GET returned')

if __name__ == '__main__':
    tornado.web.Application([
        (r'/', TestHandler),
    ]).listen(3000)
    print('Serving at 3000')
    tornado.ioloop.IOLoop.current().start()

对此TestHandler的每个请求都将创建一个新线程来运行slow_func,但是在函数返回后线程仍然保持不变。我可以在ps H中看到它们,它会创建新的线程,直到达到ulimit为止。我这里的环境是:

代码语言:javascript
复制
$ uname -a
Linux xxx 2.6.32-754.6.3.el6.x86_64 #1 SMP Tue Sep 18 10:29:08 EDT 2018 x86_64 x86_64 x86_64 GNU/Linux
$ python3 --version
Python 3.7.4
$ pip3 show tornado
Name: tornado
Version: 6.0.3
Summary: Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Home-page: http://www.tornadoweb.org/
Author: Facebook
Author-email: python-tornado@googlegroups.com
License: http://www.apache.org/licenses/LICENSE-2.0
Location: /xxx/lib/python3.7/site-packages
Requires: 
Required-by:

tornado.ioloop.IOLoop.run_in_executor使用concurrent.futures.Executor并返回一个可访问的Future对象。13

函数返回后,线程在做什么?为什么在未来的目标解决后他们不被杀死?我该怎么避免这件事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-29 10:03:17

run_in_executor接受一个concurrent.futures.Executor对象作为第一个参数。

您可以创建一个执行器并限制线程池的大小:

代码语言:javascript
复制
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor(max_workers=8)

IOLoop.current().run_in_executor(executor, slow_func) 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57707073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档