참고
https://docs.python.org/ko/3/library/asyncio-task.html
키워드
create_task, run, sleep
ㅋ couroutine 인데 오타로 corutine 이라고 적음 그런줄알고 보면됨
코루틴을 오해하고 있었음..
내가 전에 해봤던 코루틴은 메인과 서브들의 실행단계를 내가 직접 스케쥴하는 방식 이였고, 이렇게만 쓰는 줄 알았다.
예를 들면
A동작, A동작중 30%완료에서 A스탑,
B동작, B동작중 70%완료에서 B스탑,
A동작, A동작중 90%완료에서 A스탑,
B동작 100%완료
A동작 100%완료
이렇게 직접 스케쥴링 하는거
이 방식을 이용해서 asyncIO lib를 쓰는건데 , 쓰는방식은 다양하다.
lib 를 보면 그냥 다같이 켜지는 거라든가, 시간에 따라서 켜진다든가, 어떤 Event에 따라서 동작한다든가 여러 lib가 있어서 상황에 맞게 찾아서 쓰면 됨
1 run
#!/usr/bin/env python3
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
asyncio.run(main())
출력결과 : 동기식 프로그램처럼 hello 뜨고 1초뒤에 world 뜸
단순히 코루틴을 호출하는 것으로 실행되도록 예약하는건 아니다.
2 run , await
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
출력결과 : 동기식 프로그램처럼 된다.
헬로 -> 1초 -> world -> 2초 -> 끝
3초걸림
3 run , create_task : task 등록(future개념) 후 await로 run
#!/usr/bin/env python3
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
task1 = asyncio.create_task(
say_after(1,'hello'))
task2 = asyncio.create_task(
say_after(2,'world'))
print(f"finished at {time.strftime('%X')}")
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
출력결과 : 비동기식 처럼 됬다!
hello -> 1초 -> world -> 끝
2초걸림 ( 이유 : asyncio.create_task 같은 경우
이처럼 코루틴을 선언하고 따로 쓰려면 asyncio.@@@ 함수들을 사용해서 다양한 방법으로 사용해줘야 한다.
await @@@ 라고 하면
@@@은 awaitable 객체 라고 한다.
awaitable 객체는 세가지 유형이 있습니다.
1. coroutine
2. task
3. future
1,2번은 위에 나왔고 3번은 일단 keep한다.
asyncIO 함수관련
asyncio.run(coro, *, debug=False)
다른데다 올리겠다
'언어 정리 > python_비동기관련_lib' 카테고리의 다른 글
AsyncIO_5_멀티 스크랩핑 실습(인프런) (0) | 2022.06.04 |
---|---|
AsyncIO_4_{ 저수준함수 : 이벤트 루프 : asyncio.get_event_loop( ) } (0) | 2022.05.05 |
python 쓰레드 개념 (0) | 2022.05.03 |
AsyncIO_3_{함수 : asyncio.Event 라이브러리 ( wait(),set(),clear() ) } asynchronous primitive (0) | 2022.04.20 |
asyncIO_2_( asyncIO개념(Idle state, I/O wait,I/O연산) + 함수 : gather ) (0) | 2022.04.20 |
댓글