await
예를 들어 비동기 Python 코드에서 코 루틴을 사용 하면 정확히 어떤 일이 발생하는지 궁금합니다 .
await send_message(string)
(1) send_message
이벤트 루프에 추가되고 호출 코 루틴이 이벤트 루프에 대한 제어를 포기합니다.
(2) 직접 뛰어 들다 send_message
내가 읽은 대부분의 설명 은 호출 코 루틴을 exiting 으로 설명하므로 (1)을 가리 킵니다 . 그러나 내 자신의 실험은 (2)가 사례임을 시사합니다. 나는 호출자 뒤에서 호출자 앞에서 코 루틴을 실행하려고 시도했지만 이것을 달성 할 수 없었습니다.
(2) 맞습니다 asyncio.Future
. 실제로 블로킹하는 것을 기다리지 않는 한 이벤트 루프에 제어를 반환하지 않습니다 .
상속을 통해 기본 이벤트 루프 구현 을 변경하여 확인할 수 있습니다 .
import asyncio
class TestEventLoop(asyncio.SelectorEventLoop):
def _run_once(self):
print('inside event loop')
super()._run_once()
async def func2():
print('inside func2()')
await asyncio.sleep(1)
async def func1():
print('inside func1()')
await func2()
async def main():
print('inside main()')
await func1()
loop = TestEventLoop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.close()
결과:
inside event loop
inside main()
inside func1()
inside func2()
inside event loop
inside event loop
inside event loop
그러나 이것은 기본 이벤트 루프 구현의 세부 사항입니다 . 즉, 모든 종류의 이벤트 루프에 대해 (2) 사실이 보장 되지 않으며이 동작에 의존해서는 안됩니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다