PYTHON · 비동기
trio 소개
trio는 구조적 동시성을 핵심 원칙으로 하는 비동기 라이브러리입니다. asyncio의 대안으로 사용됩니다.
비동기고급trio구조적 동시성nurserycancel
핵심 설명
trio는 구조적 동시성을 핵심 원칙으로 하는 비동기 라이브러리입니다. asyncio의 대안으로 사용됩니다.
Python code
# trio 스타일을 asyncio로 시뮬레이션
import asyncio
async def child_task(name: str, delay: float):
print(f" {name} 시작")
await asyncio.sleep(delay)
print(f" {name} 완료")
return f"{name} 결과"
async def structured_concurrency():
"""trio의 nursery 패턴을 asyncio TaskGroup으로 구현"""
print("부모 태스크 시작")
# trio: async with trio.open_nursery() as nursery:
# asyncio 3.11+:
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(child_task("작업1", 1))
t2 = tg.create_task(child_task("작업2", 0.5))
t3 = tg.create_task(child_task("작업3", 1.5))
# 여기서 모든 자식 태스크가 완료됨을 보장
print("모든 자식 태스크 완료")
print(f" 결과: {t1.result()}, {t2.result()}, {t3.result()}")
async def cancellation_example():
"""취소 전파 시연"""
async def long_task():
try:
await asyncio.sleep(100)
except asyncio.CancelledError:
print(" 태스크 취소됨, 정리 중...")
raise
task = asyncio.create_task(long_task())
await asyncio.sleep(0.5)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("취소 확인됨")
asyncio.run(structured_concurrency())
asyncio.run(cancellation_example())학습 팁
trio는 pip install trio로 설치합니다. 새 프로젝트라면 trio의 깔끔한 API를 고려해보세요.
주의할 점
CancelledError를 잡고 다시 raise하지 않으면 취소가 전파되지 않아 리소스 누수가 발생합니다.
자주 묻는 질문
trio 소개란 무엇인가요?
trio 는 구조적 동시성을 핵심 원칙으로 하는 비동기 라이브러리입니다. asyncio의 대안으로 사용됩니다.
trio 소개 학습 시 주의할 점은 무엇인가요?
CancelledError 를 잡고 다시 raise하지 않으면 취소가 전파되지 않아 리소스 누수가 발생합니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.