ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python Backend] asyncio API 정리
    WEB 2025. 5. 25. 15:04
    728x90
    [Python Backend] asyncio API 정리 

    https://docs.python.org/ko/3.13/library/asyncio-task.html

     

    Coroutines and Tasks

    This section outlines high-level asyncio APIs to work with coroutines and Tasks. Coroutines, Awaitables, Creating Tasks, Task Cancellation, Task Groups, Sleeping, Running Tasks Concurrently, Eager ...

    docs.python.org

     

     

    ✅ 1. 코루틴이란?

    • async def로 만든 함수는 코루틴 함수라고 해요.
    • 코루틴은 await을 통해 비동기 작업을 잠깐 멈췄다가 다시 실행할 수 있어요.
    import asyncio
    
    async def main():
        print("hello")
        await asyncio.sleep(1)
        print("world")
    
    asyncio.run(main())
    

    출력:

    hello
    (1초 기다림)
    world
    

    그냥 main()만 실행하면 아무 일도 안 일어나요. 꼭 asyncio.run(main())처럼 실행해야 해요.


    ✅ 2. 태스크(Task)란?

    코루틴을 동시에 실행하고 싶을 때 asyncio.create_task()를 써요.
    예를 들어, 두 작업을 동시에 실행하면 시간이 절약돼요:

    async def say_after(delay, msg):
        await asyncio.sleep(delay)
        print(msg)
    
    async def main():
        task1 = asyncio.create_task(say_after(1, "hello"))
        task2 = asyncio.create_task(say_after(2, "world"))
        await task1
        await task2
    
    asyncio.run(main())
    

    출력:

    (1초 후) hello
    (2초 후) world
    

    두 작업이 동시에 실행돼서 전체 시간은 2초밖에 안 걸려요.


    ✅ 3. TaskGroup (3.11+)

    Python 3.11부터는 TaskGroup이라는 더 안전한 방식도 있어요.
    실수로 태스크를 잊지 않도록 도와주는 일종의 그룹입니다.

    async def main():
        async with asyncio.TaskGroup() as tg:
            tg.create_task(say_after(1, "hello"))
            tg.create_task(say_after(2, "world"))
    

    async with가 끝나면, 그룹 안의 모든 작업이 완료될 때까지 기다려줘요.


    ✅ 4. 동시에 여러 작업 실행하기: gather

    results = await asyncio.gather(task1(), task2(), task3())
    

    모든 작업이 한 번에 실행되고, 결과는 리스트로 반환돼요.
    중간에 에러가 나면 멈출 수도 있어요.
    (에러를 무시하고 싶으면 return_exceptions=True 설정)


    ✅ 5. 시간 초과 시 작업 멈추기: timeout, wait_for

    # 5초 안에 끝나야 함
    async with asyncio.timeout(5):
        await long_task()
    

    혹은:

    await asyncio.wait_for(long_task(), timeout=5)
    

    시간이 지나면 작업을 강제로 멈추고 TimeoutError를 발생시켜요.


    ✅ 6. 실행 중 태스크 취소하기

    task = asyncio.create_task(long_task())
    task.cancel()
    

    CancelledError가 발생하면서 작업이 멈춰요. 코루틴에서 try/finally로 정리 작업을 꼭 해주세요.


    ✅ 7. 태스크가 쓰레기 수집되면 안 되니까 꼭 변수로 저장해야 함

    background_tasks = set()
    
    for i in range(10):
        task = asyncio.create_task(do_something(i))
        background_tasks.add(task)
        task.add_done_callback(background_tasks.discard)
    

    안 그러면 작업 도중 메모리에서 사라져서 실행이 멈출 수도 있어요.


    ✅ 8. CPU나 파일 I/O 작업은 to_thread()로 스레드에 실행

    await asyncio.to_thread(blocking_func)
    

    time.sleep()이나 파일 읽기 같은 블로킹 함수를 별도 스레드에서 실행해서 이벤트 루프를 막지 않게 해줘요.


    ✅ 9. await 가능한 객체 종류 (Awaits 가능한 것들)

    • 코루틴 (async def로 만든 함수)
    • 태스크 (코루틴을 감싼 실행 예약된 객체)
    • 퓨처 (결과가 나중에 생기는 약속 같은 객체)

    요약 정리

    기능설명

    async def, await 비동기 함수 정의 및 대기
    asyncio.run() 비동기 코드 실행 시작점
    create_task() 코루틴을 태스크로 만들어 실행 예약
    TaskGroup 여러 태스크를 묶어서 안전하게 관리
    gather() 여러 작업을 동시에 실행하고 결과 모음
    timeout() 시간 초과로 작업 제한
    to_thread() 블로킹 함수를 스레드에서 비동기로 실행
    cancel() 실행 중인 태스크 취소
    shield() 특정 작업을 취소되지 않게 보호

     

    728x90
Designed by Tistory.