0Pricing
Python Academy · 강의

await, 작업 및 수집

동시성을 위해 await, asyncio.create_task 및 asyncio.gather를 사용합니다.

await, 작업 및 수집은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

await와 순차 실행 비교

await만 사용하면 코루틴이 순차적으로 실행됩니다. 코루틴을 동시에 실행하려면 작업으로 감싸십시오.

import asyncio

async def main():
    # Sequential — total ~3 s
    await asyncio.sleep(2)
    await asyncio.sleep(1)

    # Concurrent using gather — total ~2 s
    await asyncio.gather(asyncio.sleep(2), asyncio.sleep(1))

asyncio.create_task()

asyncio.create_task(coro)는 코루틴을 현재 코루틴과 동시에 실행되는 독립적인 작업으로 예약합니다.

import asyncio

async def work(n):
    await asyncio.sleep(n)
    return n

async def main():
    t1 = asyncio.create_task(work(2))
    t2 = asyncio.create_task(work(1))
    r1 = await t1
    r2 = await t2
    print(r1, r2)   # 2 1 (total ~2 s)

asyncio.run(main())

asyncio.gather()

asyncio.gather(*coros)는 코루틴을 동시에 실행하고, 모두 완료되면 모든 결과를 순서대로 반환합니다.

import asyncio

async def fetch(i):
    await asyncio.sleep(1)
    return f"data-{i}"

async def main():
    results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
    print(results)  # ["data-1", "data-2", "data-3"] in ~1 s

asyncio.run(main())

return_exceptions와 함께 gather 사용하기

return_exceptions=True로 설정하면 실패한 코루틴이 전체 gather를 취소하는 대신 예외를 결과로 반환합니다.

import asyncio

async def risky(n):
    if n == 2: raise ValueError("bad")
    return n

async def main():
    results = await asyncio.gather(
        risky(1), risky(2), risky(3),
        return_exceptions=True
    )
    print(results)   # [1, ValueError("bad"), 3]

asyncio.wait()

asyncio.wait(tasks, return_when=...)은 done과 pending이라는 두 집합을 반환합니다. 첫 번째 결과에 반응하려면 FIRST_COMPLETED를 사용하세요.

import asyncio

async def slow(): await asyncio.sleep(3); return "slow"
async def fast(): await asyncio.sleep(1); return "fast"

async def main():
    tasks = {asyncio.create_task(slow()), asyncio.create_task(fast())}
    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    for t in pending: t.cancel()

작업 취소

취소를 요청하려면 task.cancel()을 호출하세요. 작업은 다음 await 지점에서 asyncio.CancelledError를 받습니다.

import asyncio

async def long_job():
    try:
        await asyncio.sleep(100)
    except asyncio.CancelledError:
        print("Cancelled!")
        raise   # re-raise is required

async def main():
    t = asyncio.create_task(long_job())
    await asyncio.sleep(1)
    t.cancel()
    await t

asyncio.timeout() — Python 3.11 이상

asyncio.timeout(seconds)로 await 표현식을 감싸면 작업이 너무 오래 걸릴 때 해당 작업을 취소할 수 있습니다.

import asyncio

async def main():
    try:
        async with asyncio.timeout(2):
            await asyncio.sleep(10)   # too slow
    except TimeoutError:
        print("Timed out!")

asyncio.wait_for()

Python 3.11 미만에서는 asyncio.wait_for(coro, timeout=N)을 사용해 시간 제한을 추가할 수 있으며, asyncio.TimeoutError가 발생합니다.

import asyncio

async def slow(): await asyncio.sleep(5)

async def main():
    try:
        await asyncio.wait_for(slow(), timeout=2)
    except asyncio.TimeoutError:
        print("Timed out")

작업 이름 및 검사

asyncio.create_task(coro, name="...")로 작업에 이름을 지정하면 디버깅이 쉬워지고, task.get_name()으로 이름을 확인할 수 있습니다.

import asyncio

async def worker(): await asyncio.sleep(1)

async def main():
    t = asyncio.create_task(worker(), name="worker-1")
    print(t.get_name())   # worker-1
    await t

TaskGroup — Python 3.11 이상

asyncio.TaskGroup은 구조화된 작업 그룹을 만듭니다. 작업 하나라도 예외를 발생시키면 모든 작업이 취소됩니다.

import asyncio

async def main():
    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(asyncio.sleep(1))
        t2 = tg.create_task(asyncio.sleep(2))
    # all tasks done here

속도 제한을 위한 Semaphore

asyncio.Semaphore(n)을 사용해 동시에 실행되는 작업 수를 제한하세요(예: API 호출).

import asyncio

sem = asyncio.Semaphore(5)  # max 5 concurrent

async def limited_fetch(url):
    async with sem:
        await fetch(url)   # at most 5 at a time

빠른 확인

await coro()와 asyncio.create_task(coro())의 차이는 무엇입니까?

복습

동시 실행에는 create_task 또는 gather를 사용하세요. gather는 모든 결과를 수집하고, wait는 세밀하게 제어할 수 있습니다. .cancel()로 작업을 취소하고, wait_for 또는 asyncio.timeout으로 시간 제한을 적용하세요.

자주 묻는 질문

“await, 작업 및 수집” 강의는 무료인가요?

네 — “await, 작업 및 수집” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“await, 작업 및 수집”에서 뭘 배우나요?

동시성을 위해 await, asyncio.create_task 및 asyncio.gather를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Python Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“await, 작업 및 수집” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 코루틴과 이벤트 루프
  2. await, 작업 및 수집
  3. 비동기 컨텍스트 관리자와 반복자
  4. 프로덕션 환경의 비동기 입출력 패턴
← Python Academy(으)로 돌아가기