龙卷风“@run_on_executor”正在阻塞

2023-12-30

我想问一下如何龙卷风.concurrent.run_on_executor https://tornado.readthedocs.org/en/latest/concurrent.html#tornado.concurrent.run_on_executor(后来只是run_on_executor)有效,因为 我可能不明白如何运行同步任务而不阻塞主 IOLoop。

所有示例都使用run_on_executor,我发现,正在使用time来阻止循环。 和time模块它工作正常,但是当我尝试一些时间密集型计算时,使用run_on_executor,任务阻塞 IOLoop。 我可以看到该应用程序使用多个线程,但它仍然处于阻塞状态。

我想用run_on_executor用于散列密码使用bcrypt,但用此计算替换它以获得一些额外的测试时间。

这里我有一个小应用程序,来展示我的困惑。

from tornado.options import define, options
import tornado.web
import tornado.httpserver
from tornado import gen
from tornado.concurrent import run_on_executor
import tornado.httpclient
import tornado.escape
import time
import concurrent.futures
import urllib


executor = concurrent.futures.ThreadPoolExecutor(20)
define("port", default=8888, help="run on the given port", type=int)


# Should not be blocking ?
class ExpHandler(tornado.web.RequestHandler):
    _thread_pool = executor

    @gen.coroutine
    def get(self, num):
        i = int(num)
        result = yield self.exp(2, i)
        self.write(str(result))
        self.finish()

    @run_on_executor(executor="_thread_pool")
    def exp(self, x, y):
        result = x ** y
        return(result)


class NonblockingHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        try:
            response = yield http_client.fetch("http://www.google.com/")
            self.write(response.body)
        except tornado.httpclient.HTTPError as e:
            self.write(("Error: " + str(e)))
        finally:
            http_client.close()
        self.finish()


class SleepHandler(tornado.web.RequestHandler):
    _thread_pool = executor

    @gen.coroutine
    def get(self, sec):
        sec = float(sec)
        start = time.time()
        res = yield self.sleep(sec)
        self.write("Sleeped for {} s".format((time.time() - start)))
        self.finish()

    @run_on_executor(executor="_thread_pool")
    def sleep(self, sec):
        time.sleep(sec)
        return(sec)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/exp/(?P<num>[^\/]+)?', ExpHandler),
            (r'/nonblocking/?', NonblockingHandler),
            (r'/sleep/(?P<sec>[^\/]+)?',SleepHandler)
        ]
        settings = dict(
            debug=True,
            logging="debug"
        )
        tornado.web.Application.__init__(self, handlers, **settings)


def  main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    io_loop = tornado.ioloop.IOLoop.instance()
    io_loop.start()


if __name__ == "__main__":
    main()

我将非常感激任何解释为什么ExpHandler, 运行executor正在阻塞循环。


Python(至少在 CPython 实现中)有一个全局解释器锁,可以防止多个线程同时执行 Python 代码。特别是,在单个 Python 操作码中运行的任何内容都是不可中断的,除非它调用显式释放 GIL 的 C 函数。大指数**始终持有 GIL,从而阻塞所有其他 python 线程,同时调用bcrypt()将释放 GIL,以便其他线程可以继续工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

龙卷风“@run_on_executor”正在阻塞 的相关文章

随机推荐

  • 在java中查找RGB的按位版本

    我有以下方法获取 rgb 值并使用较小的调色板对其进行分类 private static int roundToNearestColor int rgb int nrColors int red rgb gt gt 16 0xFF int
  • 代码中未定义的错误

    我的 php 代码有问题 我在这两行中都得到未定义的索引 Page GET Page if GET Page 它只发生在第一页 当然它应该只发生在那时 有人可以告诉我如何解决吗 我发现了类似的东西 但我无法完全删除该通知 empty GET
  • 如何从 Ansible 设置模块的输出中获取列表的第一个元素?

    我从设置模块收到以下数据 ansible nodename 3d734bc2a391 ansible os family RedHat ansible pkg mgr yum ansible processor AuthenticAMD A
  • 检查页面上是否存在Javascript脚本

    我制作了一个书签 它将脚本从我的服务器加载到用户当前页面上 但是 我在脚本中进行了 if 检查 如果不满足条件 则不采取任何操作 但是 如果用户满足该条件 则代码将运行 但会导致将两组脚本插入到其页面中 我可以阻止这个吗 a href Bo
  • 如何在 Winforms Designer 中设置组合框的默认值?

    Locked 有对该问题内容的争议 help locked posts此时正在解决 目前不接受新的答案或互动 我正在使用 Visual Studio 2010 用 C 编写一个 Windows 窗体应用程序 它有一个组合框 我已经设置了Dr
  • 如何在 Gradle 中设置 Kotlin 源编码?

    使用 Gradle 构建 Java 或 Groovy 时 可以像这样定义源编码 compileJava options encoding UTF 8 compileTestJava options encoding UTF 8 compil
  • 如何限制对 Elmah 的远程访问?

    在我们的开发 Web 服务器上安装 Elmah 后 我们可以限制谁远程访问它吗 即使我们对用户名 密码进行硬编码 散列 还是仅通过 IP 有两种设置 一种是在
  • 在构造函数重载的情况下如何调用 super(...) 和 this(...) ?

    我以前从未需要这样做 但由于两者都必须是构造函数中的 第一 行 应该如何处理它 对于这种情况 最好的重构是什么 这是一个示例 public class Agreement extends Postable public Agreement
  • 使 LinearLayout 像 Button 一样工作

    我有一个LinearLayout我设计得看起来像button 它包含一些文本 ImageView 元素 我想做整体LinearLayout表现得像一个button 特别是赋予它在 a 中定义的状态 以便在按下时它具有不同的背景 有没有比制作
  • 浏览器窗口中的所有选项卡是否共享一个 JavaScript 线程?

    一般来说 浏览器中的 JavaScript 执行被认为是单线程的 这个单一线程是否适用于浏览器窗口中打开的所有选项卡 换句话说 如果 不同的 JavaScript 代码在不同的选项卡中运行 它们都是使用单个线程执行的吗 此外 当您打开同一浏
  • 将seaborn图例移动到不同的位置

    我在用着factorplot kind bar 与海博恩 情节很好 只是图例放错了位置 太靠右 文本超出了情节的阴影区域 如何让seaborn将图例放在其他地方 例如左上角而不是右中 基于 user308827的答案 你可以使用legend
  • 我可以在 Facebook 应用程序上设置页面选项卡高度吗?

    我使用以下命令创建了一个 Facebook 页面选项卡应用程序Heroku 托管选项 https devcenter heroku com articles facebook 我看到一个用于将 页面选项卡 宽度设置为 正常 810 像素 或
  • Raphaël 对象:模拟点击

    是否可以模拟拉斐尔对象上的点击 我已经尝试过了 object click Error click is not a function or object dispatchEvent click Error Could not convert
  • 使用 java Mapreduce 处理 JSON

    我是 hadoop mapreduce 新手 我输入了文本文件 其中数据已存储如下 这里只有几个元组 data txt author Shari f Qa sim book al Rabi al manshu d author Na s i
  • 传递给 Rust WebAssembly 模块时 JavaScript 字符串为空

    当将字符串传递给 Rust WASM 模块时 传递的数据显示为空白 根据模式匹配real code compute功能 以下代码是我尝试过的 我不知道这是否与它的返回方式有关 但是当我传递硬编码时 str 效果很好 但是 那JsIntero
  • 验证:仅字母、数字和 -

    我想验证我的用户 因此他们只能在用户名中使用 a z 和 validates format of username with gt a z 然而这条规则也允许空格 Username should use only letters numbe
  • Oauth 错误 invalid_request:redirect_uri 未列入白名单

    我正在尝试基于此使用 React 和 Node 开发一个应用程序文档 https developers shopify com tutorials build a shopify app with node and react 我一步步按照
  • ListenableWorker 不删除通知图标

    我正在使用 ListenableWorker 执行后台任务 另外我希望操作系统了解我的服务重要性 所以我打电话 setForegroundAsync new ForegroundInfo WorkerConstants NOTIFICATI
  • 文本变量不起作用

    我正在尝试从 Tkinter 中的 Entry 小部件中获取文本 它适用于 Entry1 get 但不适用于 textvariable 我究竟做错了什么 from Tkinter import master Tk v StringVar d
  • 龙卷风“@run_on_executor”正在阻塞

    我想问一下如何龙卷风 concurrent run on executor https tornado readthedocs org en latest concurrent html tornado concurrent run on