在自己的线程

时间:2017-07-11 15:57:03

标签: python python-multithreading python-asyncio

我正在玩Python的新(ish)asyncio内容,试图将其事件循环与传统的线程结合起来。我编写了一个类,它在自己的线程中运行事件循环,以隔离它,然后提供一个(同步)方法,在该循环上运行协程并返回结果。 (我意识到这使得它成为一个毫无意义的例子,因为它必然会将所有内容序列化,但它只是作为一个概念验证)。

import asyncio
import aiohttp
from threading import Thread


class Fetcher(object):
    def __init__(self):
        self._loop = asyncio.new_event_loop()
        # FIXME Do I need this? It works either way...
        #asyncio.set_event_loop(self._loop)

        self._session = aiohttp.ClientSession(loop=self._loop)

        self._thread = Thread(target=self._loop.run_forever)
        self._thread.start()

    def __enter__(self):
        return self

    def __exit__(self, *e):
        self._session.close()
        self._loop.call_soon_threadsafe(self._loop.stop)
        self._thread.join()
        self._loop.close()

    def __call__(self, url:str) -> str:
        # FIXME Can I not get a future from some method of the loop?
        future = asyncio.run_coroutine_threadsafe(self._get_response(url), self._loop)
        return future.result()

    async def _get_response(self, url:str) -> str:
        async with self._session.get(url) as response:
            assert response.status == 200
            return await response.text()


if __name__ == "__main__":
    with Fetcher() as fetcher:
        while True:
            x = input("> ")

            if x.lower() == "exit":
                break

            try:
                print(fetcher(x))
            except Exception as e:
                print(f"WTF? {e.__class__.__name__}")

为了避免这听起来太像'" Code Review"问题,asynchio.set_event_loop的目的是什么,我在上面需要它吗?无论有没有,它都能正常工作。此外,是否有一个循环级方法来调用协程并返回未来?使用模块级功能执行此操作似乎有点奇怪。

2 个答案:

答案 0 :(得分:2)

如果您在任何地方拨打set_event_loop并希望它返回您拨打get_event_loop时创建的循环,则需要使用new_event_loop

来自docs

  

如果需要将此循环设置为当前上下文的事件循环,则必须显式调用set_event_loop()

由于您未在示例中的任何位置拨打get_event_loop,因此可以省略对set_event_loop的调用。

答案 1 :(得分:0)

我可能会误解,但我认为@dirn在已标记答案中的评论是错误的,它表明get_event_loop是从线程工作的。请参见以下示例:

import asyncio
import threading

async def hello():
    print('started hello')
    await asyncio.sleep(5)
    print('finished hello')

def threaded_func():
    el = asyncio.get_event_loop()
    el.run_until_complete(hello())

thread = threading.Thread(target=threaded_func)
thread.start()

这会产生以下错误:

RuntimeError: There is no current event loop in thread 'Thread-1'.

可以通过以下方式修复:

 - el = asyncio.get_event_loop()
 + el = asyncio.new_event_loop()

documentation还指定此技巧(通过调用get_event_loop创建事件循环)仅适用于主线程:

如果当前OS线程中没有设置当前事件循环,则OS线程为main,并且尚未调用set_event_loop(),asyncio将创建一个新的事件循环并将其设置为当前事件循环。 >

最后,如果您使用的是3.7版或更高版本,则文档还建议使用get_running_loop而不是get_event_loop