在工作线程/循环中运行异步函数

时间:2021-05-03 02:53:48

标签: python python-asyncio event-loop thread-synchronization asyncpg

我正在尝试编写代码,以便能够从大部分同步代码中使用 asyncpg(以避免重复)。 由于一些非常奇怪的原因,协程 Database.test() 将在我的工作事件循环/线程中执行并返回。未来似乎工作正常。但是使用 asyncpg 连接到数据库只会挂起。知道原因吗?

另外,也许我应该改用 asyncio.run()。

from threading import Thread
import asyncio
import asyncpg

class AsyncioWorkerThread(Thread):

    def __init__(self, *args, daemon=True, loop=None, **kwargs):
        super().__init__(*args, daemon=daemon, **kwargs)
        self.loop = loop or asyncio.new_event_loop()
        self.running = False

    def run(self):
        self.running = True
        self.loop.run_forever()

    def submit(self, coro):
        fut = asyncio.run_coroutine_threadsafe(coro, loop=self.loop)
        return fut.result()

    def stop(self):
        self.loop.call_soon_threadsafe(self.loop.stop)
        self.join()
        self.running = False

class Database:
    async def test(self):
        print('In test')
        await asyncio.sleep(5)

    async def connect(self):
        # Put in your db credentials here
        # pg_user = ''
        # pg _password = ''
        # pg_host = ""
        # pg_port = 20
        # pg_db
        connection_uri = f'postgres://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_db}'
        self.connection_pool = await asyncpg.create_pool(
            connection_uri, min_size=5, max_size=10)

if __name__ == "__main__":
    db = Database()
    worker = AsyncioWorkerThread()
    worker.start()
    worker.submit(db.test())  # Works future returns correctly
    worker.submit(db.connect())  # Hangs, thread never manages to acquire

0 个答案:

没有答案