为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2021-06-03 15:28:48
我正在尝试创建两个线程,每个线程都有自己的异步事件循环。我已经尝试了以下代码,但似乎不起作用:import asynciofrom threading import Threaddef 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 异步函数。
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号