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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值