在使用tornado時,經常有人疑惑IOLoop.instance()方法和IOLoop.current()方法的區別是什么。
IOLoop.instance()
返回一個全局 IOLoop實例。
大多數應用程序在主線程上運行着一個全局IOLoop,使用IOLoop.instance()方法可以在其他線程上獲取這個實例。
返回當前線程的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