是否可以使线程运行方法异步,以便它可以在其中执行协程?我意识到我正在混合范例 - 我正在尝试集成使用协程的第三方库,而我的项目使用线程。在考虑更新我的项目以使用协程之前,我想探索在线程中执行协程。
下面是我的示例用例,其中我有一个线程,但我想从线程内调用协程。我的问题是功能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
您需要创建一个 asyncio 事件循环,并等待协程完成。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)