是否可以使线程运行方法异步,以便它可以在其中执行协程?我意识到我正在混合范例——我正在尝试集成一个使用协程的第三方库,而我的项目使用线程。在我考虑更新我的项目以使用协程之前,我想探索在我的线程中执行协程。
下面是我的示例用例,其中我有一个线程,但我想从我的线程中调用协程。我的问题是函数 MyThread::run() 似乎没有执行(打印)。我正在尝试的方法是否可行……并且可取?
from threading import Thread
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.start()
# def run(self):
# while True:
# print("MyThread::run() sync")
async def run(self):
while True:
# This line isn't executing/printing
print("MyThread::run() sync")
# Call coroutine...
# volume = await market_place.get_24h_volume()
try:
t = MyThread()
while True:
pass
except KeyboardInterrupt:
pass
请您参考如下方法:
您需要创建一个异步事件循环,并等待协程完成。
import asyncio
from threading import Thread
class MyThread(Thread):
def run(self):
loop = asyncio.new_event_loop() # loop = asyncio.get_event_loop()
loop.run_until_complete(self._run())
loop.close()
# asyncio.run(self._run()) In Python 3.7+
async def _run(self):
while True:
print("MyThread::run() sync")
await asyncio.sleep(1)
# OR
# volume = await market_place.get_24h_volume()
t = MyThread()
t.start()
try:
t.join()
except KeyboardInterrupt:
pass
