[英]How do I set the asyncio event loop for a thread in Python?
我正在尝试创建两个线程,每个线程都有自己的asyncio事件循环。
我尝试了以下代码,但它似乎不起作用:
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异步函数。
您的线程在各自的事件循环中排队回调,但它们在实际运行事件循环之前退出,因此回调永远不会被执行。 此外,您不需要call_soon_threadsafe
,因为您正在从同一个线程调用事件循环(或者更确切地说,将要运行)。
此代码打印预期输出:
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(lambda: hello('a'))
event_loop_a.run_forever()
def callback_b():
asyncio.set_event_loop(event_loop_b)
asyncio.get_event_loop().call_soon(lambda: hello('b'))
event_loop_b.run_forever()
thread_a = Thread(target=callback_a, daemon=True)
thread_b = Thread(target=callback_b, daemon=True)
thread_a.start()
thread_b.start()
call_soon_threadsafe
一个更典型的用例,更符合您的想法,是将回调(或使用asyncio.run_coroutine_threadsafe
的协程)提交给在另一个线程中运行的事件循环。 这是一个例子:
import asyncio, threading
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 run_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
threading.Thread(target=lambda: run_loop(event_loop_a)).start()
threading.Thread(target=lambda: run_loop(event_loop_b)).start()
event_loop_a.call_soon_threadsafe(lambda: hello('a'))
event_loop_b.call_soon_threadsafe(lambda: hello('b'))
event_loop_a.call_soon_threadsafe(event_loop_a.stop)
event_loop_b.call_soon_threadsafe(event_loop_b.stop)
在这种情况下,很少需要有多个事件循环线程 - 您通常只创建一个,并允许该线程为您的所有asyncio需求提供服务。 毕竟,能够在单个事件循环中托管大量任务是asyncio的优势之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.