天天看點

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
           
上一篇: tornado ioloop

繼續閱讀