首页
学习
活动
专区
圈层
工具
发布

07 | Tornado源码分析:IOLoop之instance or current ?

hello,各位好,上期聊完Configurable 中最核心的内容后 我们再回来到我们之前说的 IOLoop 中,通过之前的介绍 我们已经知道了 Tornado 在实例化 IOLoop 之前 通过Configurable类的工厂方法模式自动选择了底层是基于Select 、Epoll等来做我们的多路复用的"核心"。好,选择完毕后 就面临着实例化了 那 IOLoop 中的instance 、current 这两个方法 我们应该如何选择呢?之前常有人被问到 这两者如何选择 以及适用场景 本期我们就来为大家剖析源码中的这段。 我们先看一下源文件:

instance: 大多数应用程序都在主线程上运行一个全局 IOLoop 。使用此方法从另一个线程获取此实例。在大多数其他情况下,最好使用 current 获取当前线程的 IOLoop 。 current: 返回当前线程的 IOLoop 。 若IOLoop当前正在运行或者已经标记为 current by make_current, 则返回该实例。 若没有当前的 IOLoop ,返回 IOLoop.instance 实例,即主线程的 IOLoop,必要的时候创建一个。 通常,你应该使用 IOLoop.current 作为构造异步对象 当你打算从另外一个线程与主线程进行通信的时候使用IOLoop.instance。 总结一下: 第一、IOLoop.instance() 1.返回一个全局 IOLoop实例 2.大多数应用程序在主线程上运行着一个全局IOLoop,使IOLoop.instance()方法可以在其他线程上获取这个实例。 第二、IOLoop.current() 1.返回当前线程的IOLoop,如果IOLoop当前正在运行或已被make_current标记为当前,则返回该实例。如果没有当前IOLoop,默认情况下返回IOLoop.instance(),即返回主线程的IOLoop,如果没有,则进行创建。 2.一般情况下,当构造异步对象时,你默认应该使用IOLoop.current(),当你在另外一个线程上和主线程进行通信时,使用IOLoop.instance()。

注意:

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

我们再通过一个简单的demo 程序来说明一下:

代码语言:javascript
复制
# -*- encoding: utf-8 -*-
# !/usr/bin/python
"""
@File    : demo.py
@Time    : 2020/6/14 15:39
@Author  : haishiniu
@Software: PyCharm
"""
import tornado.ioloop

# 此时_current没有instance
print('instance' in dir(tornado.ioloop.IOLoop._current))

# 通过instance IOLoop() 会设置当前_current instance
a1 = tornado.ioloop.IOLoop.current()
print(id(a1))

print('instance' in dir(tornado.ioloop.IOLoop._current))
# 直接获取当前线程初始化了的_current.instance
b1 = tornado.ioloop.IOLoop.current()
print(id(b1))


a2 = tornado.ioloop.IOLoop.instance()
print(id(a2))

b2 = tornado.ioloop.IOLoop.instance()
print(id(b2))

好的,本期的分享到此就结束了,以后在使用具体的方法来创建实例的时候就知其然也知其所以然了,后续我们会接着看 IOLoop 这个类中的其他东西,敬请期待!

下一篇
举报
领券