tornado的IOLoop.instance()方法和IOLoop.current()方法区别

在使用tornado时,经常有人疑惑IOLoop.instance()方法和IOLoop.current()方法的区别是什么。

IOLoop.instance()

返回一个全局 IOLoop实例。

大多数应用程序在主线程上运行着一个全局IOLoop,使用IOLoop.instance()方法可以在其他线程上获取这个实例。

IOLoop.current() 

返回当前线程的IOLoop,如果IOLoop当前正在运行或已被make_current标记为当前,则返回该实例。如果没有当前IOLoop,默认情况下返回IOLoop.instance(),即返回主线程的IOLoop,如果没有,则进行创建。

 一般情况下,当构造异步对象时,你默认应该使用IOLoop.current(),当你在另外一个线程上和主线程进行通信时,使用IOLoop.instance()。

在tornado 5.0之后的版本,instance()已经成为current()的别称,即就是调用instance方法时,实际上调用的是current方法。

贴一下源码

    def instance():
        return IOLoop.current()
    def current(instance=True):
        if asyncio is None:
            current = getattr(IOLoop._current, "instance", None)
            if current is None and instance:
                current = IOLoop()
                if IOLoop._current.instance is not current:
                    raise RuntimeError("new IOLoop did not become current")
        else:
            try:
                loop = asyncio.get_event_loop()
            except (RuntimeError, AssertionError):
                if not instance:
                    return None
                raise
            try:
                return IOLoop._ioloop_for_asyncio[loop]
            except KeyError:
                if instance:
                    from tornado.platform.asyncio import AsyncIOMainLoop
                    current = AsyncIOMainLoop(make_current=True)
                else:
                    current = None
        return current
原文地址:https://www.cnblogs.com/lucky-heng/p/10152995.html