如何在 Python 中为线程设置异步事件循环?

我正在尝试创建两个线程,每个线程都有自己的异步事件循环。


我已经尝试了以下代码,但似乎不起作用:


import asyncio

from threading import Thread


def hello(thread_name):

    print('hello from thread {}!'.format(thread_name))


event_loop_a = asyncio.new_event_loop()

event_loop_b = asyncio.new_event_loop()


def callback_a():

    asyncio.set_event_loop(event_loop_a)

    asyncio.get_event_loop().call_soon_threadsafe(lambda: hello('a'))


def callback_b():

    asyncio.set_event_loop(event_loop_b)

    asyncio.get_event_loop().call_soon_threadsafe(lambda: hello('b'))


thread_a = Thread(target=callback_a, daemon=True)

thread_b = Thread(target=callback_b, daemon=True)

thread_a.start()

thread_b.start()

我的用例是调用 Tornado Web 框架的 websocket_connect 异步函数。


绝地无双
浏览 209回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python