본문 바로가기
언어 정리/python_비동기관련_lib

AsyncIO_3_{함수 : asyncio.Event 라이브러리 ( wait(),set(),clear() ) } asynchronous primitive

by 알 수 없는 사용자 2022. 4. 20.

참고

https://docs.python.org/3/library/asyncio-sync.html?highlight=wait#asyncio.Event.wait

 

 


코드

import asyncio

async def waiter(event):
    print('waiting for it ...')
    await event.wait()
    print('... got it!')

async def main():
    # Create an Event object.
    event = asyncio.Event()

    # Spawn a Task to wait until 'event' is set.
    waiter_task = asyncio.create_task(waiter(event))

    # Sleep for 1 second and set the event.
    await asyncio.sleep(1)
    event.set()

    # Wait until the waiter task is finished.
    await waiter_task

asyncio.run(main())

결과

1.

코드대로 실행한 부분

 

2.

event.set()

이부분 주석처리시,

 

이거를 주석처리하면 ... got it! 부분이 실행안됨.

이유 : 코루틴 task 에 등록된 함수에 await event.wait() 부분때문임

event.set() 함수로 event 를 set 시켜줘야 await event.wait() 부분을 넘어감

+ await waiter_task 부분 : 코루틴 task에 등록된 함수들이 끝날때 까지 main 대기 하라는 뜻 -> 그래서 파일 종료 안됨

 

3.

    event.set()

    # Wait until the waiter task is finished.
    await waiter_task

이부분 두줄 다 주석처리,

2번과 다르게 코루틴 task에 등록된 함수가 끝나지 않았는데도

프로그램 종료된다.

 


 

이벤트 개체입니다. 스레드 세이프가 아닙니다.( 쓰레드에 안전하지 않음 )

비동기화 이벤트를 사용하여 여러 비동기화 작업에 일부 이벤트가 발생했음을 알릴 수 있습니다.

이벤트 개체는 set() 메서드에서 true로 설정하고 clear() 메서드에서 false로 재설정할 수 있는 내부 플래그를 관리합니다. wait() 메서드는 플래그가 true로 설정될 때까지 차단합니다. 이 플래그는 처음에 false로 설정됩니다.

 

asyncio.Event().wait()

Wait until the event is set.

If the event is set, return True immediately. Otherwise block until another task calls set().

Event().set()함수 신호 대기

 

asyncio.Event().set()

Set the event.

All tasks waiting for event to be set will be immediately awakened.

asyncio.Event().wait() 함수 깨우는 용도

 

asyncio.Event().clear()

Clear (unset) the event.

Tasks awaiting on wait() will now block until the set() method is called again.

asyncio.Event().wait() 함수 재움

 

asyncio.Event().is_set()

Return True if the event is set.

 


댓글