【问题标题】:Tornado Coroutine - Custom functionTornado 协程 - 自定义函数
【发布时间】:2016-07-01 16:46:02
【问题描述】:

我正在了解 Tornado 中的协程,所以让我们保持一切简单,粘贴的代码越多越好。

我想要的是使我的自制函数异步。

我可以在文档中找到的所有示例都属于同一个“隐藏”部分:AsyncHTTPClient。我不想进行 HTTP 调用。所以请不要给我那个班的例子。我有兴趣从头开始创造一些东西。我已经在Tornado coroutine上尝试了所有可能性

目前我一直在用 bash sleep 进行测试。代码如下:

import tornado.web
import tornado.httpserver
import tornado.gen
import tornado.concurrent
import subprocess
import os

@tornado.gen.coroutine
def letswait():
    fut = tornado.concurrent.Future()
    subprocess.check_output(["sleep", "5"])
    fut.set_result(42)
    return fut

class TestHandler1(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        value = yield letswait()
        self.render("test.html", num=value)

class TestHandler2(tornado.web.RequestHandler):
    def get(self):
        self.render("test.html", num=66)

class Application(tornado.web.Application):
    def __init__(self):
        DIRNAME = os.path.dirname(__file__)
        STATIC_PATH = os.path.join(DIRNAME, '../static')
        TEMPLATE_PATH = os.path.join(DIRNAME, '../template')
        sets = {
            "template_path":TEMPLATE_PATH,
            "static_path":STATIC_PATH,
            "debug":True,
        }
        tornado.web.Application.__init__(self, [
            (r"/test1", TestHandler1),
            (r"/test2", TestHandler2),
        ], **sets)

def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(8888)
    print "Let s start"
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

但是,如果我访问 test1,那么我需要等待调用返回,然后才能访问 test2。据我了解,我需要使用gen.sleep(5)。但这只是一个例子。假设我没有在 bash 上运行 sleep 5,而是运行 ssh somewhere 'do_something',这需要一些时间来运行。

有人告诉我“这个函数不是异步的”。所以我的问题是如何使自定义函数异步?

编辑:经过一番搜索,我发现这里有 tornado.process https://gist.github.com/FZambia/5756470 可以使用。但是我的子流程来自第 3 方,所以它不是我可以覆盖的东西。所以我的问题也是,如何将 3rd 方库与该 gen.coroutine 系统集成?

解决方案:感谢下面的 cmets,我找到了解决方案:

import tornado.web
import tornado.httpserver
import tornado.gen
import tornado.concurrent
import subprocess
import os

from concurrent import futures

# Create a threadpool, and this can be shared around different python files
# which will not re-create 10 threadpools when we call it.
# we can a handful of executors for running synchronous tasks

# Create a 10 thread threadpool that we can use to call any synchronous/blocking functions
executor = futures.ThreadPoolExecutor(10)

def letswait():
    result_future = tornado.concurrent.Future()
    subprocess.check_output(["sleep", "5"])
    result_future.set_result(42)
    return result_future

class TestHandler1(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        value = yield executor.submit(letswait)
        self.render("test.html", num=value)

class TestHandler2(tornado.web.RequestHandler):
    def get(self):
        self.render("test.html", num=66)

class Application(tornado.web.Application):
    def __init__(self):
        DIRNAME = os.path.dirname(__file__)
        STATIC_PATH = os.path.join(DIRNAME, '../static')
        TEMPLATE_PATH = os.path.join(DIRNAME, '../template')
        sets = {
            "template_path":TEMPLATE_PATH,
            "static_path":STATIC_PATH,
            "debug":True,
        }
        tornado.web.Application.__init__(self, [
            (r"/test1", TestHandler1),
            (r"/test2", TestHandler2),
        ], **sets)

def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(8888)
    print "Let s start"
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

【问题讨论】:

  • 您可以尝试删除 .result() 吗?那是我的错误。产量应该自动得到结果。有可能你正在等待 result(),它变成了阻塞。

标签: python asynchronous tornado


【解决方案1】:

我在这里问过类似的问题:Python Tornado - Confused how to convert a blocking function into a non-blocking function

问题是您的函数可能受 CPU 限制,唯一的方法是使用执行程序。

from concurrent import futures

# Create a threadpool, and this can be shared around different python files
# which will not re-create 10 threadpools when we call it.
# we can a handful of executors for running synchronous tasks

# Create a 10 thread threadpool that we can use to call any synchronous/blocking functions
executor = futures.ThreadPoolExecutor(10)

然后你可以这样做:

@gen.coroutine
def get(self):
    json = yield executor.submit(some_long_running_function)

这个任务将被搁置一旁,独立运行,因为有一个yield关键字,tornado会做一些其他的事情,同时在它当前运行的和你的进程之间做一个纯线程切换。这对我来说似乎工作得很好。

也就是说,你可以将子进程包裹在executor中,它会被异步处理。

如果你不想使用执行器,看来你的函数需要以状态机的方式实现。

另一篇文章:https://emptysqua.re/blog/motor-internals-how-i-asynchronized-a-synchronous-library/

请注意,Momoko (Postgres) 和 Motor (MongoDB) 都是 I/O Bound。

编辑: 我不确定你对 Tornado 有什么用处。我在执行大量 I/O 时使用 Tornado,因为我受 I/O 限制。但是,我想如果你的使用更多地受 CPU 限制,你可能想看看 Flask。您可以轻松地使用 Gunicorn 和 Flask 来创建简单的东西,并利用多个内核。尝试在 Tornado 中使用多线程或多核可能会给您带来很多麻烦,因为 Tornado 中的很多东西都不是线程安全的。

编辑 2:删除了 .result() 调用。

【讨论】:

  • 你会在你的 some_long_running_function 中加入什么?我已按照您的建议更改了测试...仍然没有运气(检查更新)。
  • 你能给我看看你的代码吗?长时间运行的函数基本上是不带括号的函数名。任何变量都用逗号传递。
  • 就是这样!我正在更新我的问题以提供解决方案
  • 没问题。对 .result() 调用感到抱歉。
猜你喜欢
  • 1970-01-01
  • 2015-06-26
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 2020-10-16
  • 2015-07-02
  • 2019-12-28
相关资源
最近更新 更多