gpt4 book ai didi

python - Thread 内调用协程

转载 作者:太空宇宙 更新时间:2023-11-04 05:04:33 25 4
gpt4 key购买 nike

是否可以使线程运行方法异步,以便它可以在其中执行协程?我意识到我正在混合范例——我正在尝试集成一个使用协程的第三方库,而我的项目使用线程。在我考虑更新我的项目以使用协程之前,我想探索在我的线程中执行协程。

下面是我的示例用例,其中我有一个线程,但我想从我的线程中调用协程。我的问题是函数 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

关于python - Thread 内调用协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com