解決async 運行多線程時報錯RuntimeError: There is no current event loop in thread 'Thread-2'

原來使用:html

loop = asyncio.get_event_loop()
task = asyncio.ensure_future(do_work(checker))
loop.run_until_complete(asyncio.wait([task]))
st = task.result()
修改後使用:
添加了
new_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(new_loop)

  

添加後以下:
new_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(new_loop)
    loop = asyncio.get_event_loop()
    task = asyncio.ensure_future(do_work(checker))
    loop.run_until_complete(asyncio.wait([task]))
    st = task.result()

  根本緣由在源碼中:python

def get_event_loop(self):
    """Get the event loop.
    This may be None or an instance of EventLoop.
    """
    if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
        self.set_event_loop(self.new_event_loop())

    if self._local._loop is None:
        raise RuntimeError('There is no current event loop in thread %r.'
                            % threading.current_thread().name)

    return self._local._loop

  

在主線程中,調用get_event_loop總能返回屬於主線程的event loop對象,若是是處於非主線程中,還須要調用set_event_loop方法指定一個event loop對象,這樣get_event_loop纔會獲取到被標記的event loop對象:git

def set_event_loop(self, loop):
    """Set the event loop."""
    self._local._set_called = True
    assert loop is None or isinstance(loop, AbstractEventLoop)
    self._local._loop = loop

  


官方文檔: https://docs.python.org/3/library/asyncio-eventloop.html
我只截取上述用到的部分具體詳情請前往官方 https://docs.python.org/3/library/asyncio-eventloop.html
 

事件循環

源代碼: Lib / asyncio / events.py, Lib / asyncio / base_events.pygithub


前言網絡

事件循環是每一個異步應用程序的核心。事件循環運行異步任務和回調,執行網絡IO操做並運行子流程。框架

應用程序開發人員一般應使用高級異步函數(例如)asyncio.run(),而且幾乎不須要引用循環對象或調用其方法。本部分主要面向須要更好地控制事件循環行爲的較低級代碼,庫和框架的做者。異步

獲取事件循環async

如下低級函數可用於獲取,設置或建立事件循環:函數

asyncio. get_running_loop

返回當前OS線程中的運行事件循環。oop

若是沒有正在運行的事件循環,RuntimeError則會引起一個。只能從協程或回調中調用此函數。

3.7版中的新功能。

asyncio. get_event_loop

獲取當前事件循環。若是當前OS線程set_event_loop()中沒有設置當前事件循環而且還沒有調用,那麼asyncio將建立一個新的事件循環並將其設置爲當前事件循環。

由於此函數具備至關複雜的行爲(尤爲是在使用自定義事件循環策略時),因此 在協程和回調中get_running_loop()首選使用此 函數get_event_loop()

還能夠考慮使用該asyncio.run()函數,而不要使用較低級別的函數來手動建立和關閉事件循環。

asyncio. set_event_loop 循環

loop設置爲當前OS線程的當前事件循環。

asyncio. new_event_loop

建立一個新的事件循環對象。

須要注意的是行爲get_event_loop()set_event_loop()new_event_loop()功能均可以經過改變 設置自定義事件循環政策

 

 asyncio 官方文檔地址https://docs.python.org/3/library/asyncio.html

相關文章
相關標籤/搜索