【发布时间】:2019-02-17 07:35:10
【问题描述】:
我正在尝试创建两个线程,每个线程都有自己的异步事件循环。
我已经尝试了以下代码,但它似乎不起作用:
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 异步函数。
【问题讨论】:
-
“它似乎不起作用”是什么意思?你有例外吗?事件循环没有运行吗?
-
事件循环没有运行,没有例外,但似乎没有在线程中设置事件循环
标签: python python-3.x multithreading python-asyncio