我正在尝试了解 asyncio 模块并使用 run_coroutine_threadsafe 函数花费大约一个小时,我什至来到了工作示例,它按预期工作,但有几个限制。
首先,我不明白我应该如何在主(任何其他)线程中正确调用 asyncio 循环,在示例中我调用它run_until_complete
并给它一个协程以使其忙于某些事情,直到另一个线程不会给它一个协程。我还有哪些其他选择?
在现实生活中我必须混合 asyncio 和线程(在 Python 中)的情况是什么?因为据我了解,asyncio 应该取代 Python 中的线程(由于 GIL 不是 IO 操作),如果我错了,请不要生气并分享您的建议。
Python 版本为 3.7/3.8
import asyncio
import threading
import time
async def coro_func():
return await asyncio.sleep(3, 42)
def another_thread(_loop):
coro = coro_func() # is local thread coroutine which we would like to run in another thread
# _loop is a loop which was created in another thread
future = asyncio.run_coroutine_threadsafe(coro, _loop)
print(f"{threading.current_thread().name}: {future.result()}")
time.sleep(15)
print(f"{threading.current_thread().name} is Finished")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
main_th_cor = asyncio.sleep(10)
# main_th_cor is used to make loop busy with something until another_thread will not send coroutine to it
print("START MAIN")
x = threading.Thread(target=another_thread, args=(loop, ), name="Some_Thread")
x.start()
time.sleep(1)
loop.run_until_complete(main_th_cor)
print("FINISH MAIN")