我正在尝试理解asyncio模块,并花费了大约一个小时的时间来使用run_coroutine_threadsafe函数,我甚至找到了一个工作示例,它按预期工作,但有一些限制。
首先,我不明白如何在主(或任何其他)线程中正确调用asyncio循环,在示例中,我使用run_until_complete
调用它,并给它一个协程,使其忙于某些事情,直到另一个线程给它一个协程。我还有什么其他选择?
在实际生活中,什么情况下我必须混合使用asyncio和线程(在Python中)?由于GIL对于非IO操作,我认为asyncio应该取代Python中的线程。如果我错了,请不要生气并分享您的建议。
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")