是否可以列出所有被阻止的龙卷风协程

is it possible to list all blocked tornado coroutines

我有一个用 tornado 编写的 "gateway" 应用程序,使用 @tornado.gen.coroutine 将信息从一个处理程序传输到另一个处理程序。我正在尝试进行一些 debugging/status 测试。我希望能够做的是枚举所有当前 blocked/waiting 在给定时刻处于活动状态的协程。在龙卷风的某个地方可以访问此信息吗?

你可能会谈论 ioloop _handlers dict。尝试在定期回调中添加:

def print_current_handlers():
    io_loop = ioloop.IOLoop.current()
    print io_loop._handlers

update: 我检查了源代码,现在认为没有简单的方法来跟踪电流 运行 gen.corouitines,A. Jesse Jiryu戴维斯是对的!

但是您可以跟踪来自协程的所有 "async" 次调用(收益)——来自生成器的每个收益都进入 IOLoop.add_callback (http://www.tornadoweb.org/en/stable/ioloop.html#callbacks-and-timeouts)

因此,通过检查 io_loop._callbacks,您可以了解 ioloop 现在的产量。

这里有很多有趣的东西:) https://github.com/tornadoweb/tornado/blob/master/tornado/gen.py

不,没有,但您或许可以创建自己的装饰器来包装 gen.coroutine,然后在协程开始时更新数据结构。

import weakref
import functools

from tornado import gen
from tornado.ioloop import IOLoop

all_coroutines = weakref.WeakKeyDictionary()


def tracked_coroutine(fn):
    coro = gen.coroutine(fn)

    @functools.wraps(coro)
    def start(*args, **kwargs):
        future = coro(*args, **kwargs)
        all_coroutines[future] = str(fn)
        return future

    return start


@tracked_coroutine
def five_second_coroutine():
    yield gen.sleep(5)


@tracked_coroutine
def ten_second_coroutine():
    yield gen.sleep(10)


@gen.coroutine
def tracker():
    while True:
        running = list(all_coroutines.values()) 
        print(running)
        yield gen.sleep(1)


loop = IOLoop.current()
loop.spawn_callback(tracker)
loop.spawn_callback(five_second_coroutine)
loop.spawn_callback(ten_second_coroutine)
loop.start()

如果您 运行 此脚本几秒钟,您将看到两个活动协程,然后是一个,然后是 none。

注意 warning in the docs about the dictionary changing size,你应该在 "tracker" 中捕获 "RuntimeError" 来解决这个问题。

这有点复杂,您可以通过打开 Tornado 的日志记录并使用 set_blocking_log_threshold.

更简单地获得所需的一切