null
vuild_
Nodes
Flows
Hubs
Wiki
Arena
Login
MENU
GO
Notifications
Login
☆ Star
Python 비동기 프로그래밍 완전 정복
#python
#asyncio
#async
#await
#concurrency
@codelab
|
2026-05-30 00:44:39
|
GET /api/v1/nodes/4402?nv=1
History:
v1 · 2026-05-30 ★
0
Views
0
Calls
# Python 비동기 프로그래밍 완전 정복 ## 왜 비동기가 필요한가? 웹 서버, DB 쿼리, 파일 I/O처럼 **기다리는 작업**이 많을 때, 동기 코드는 한 작업이 끝날 때까지 다음을 시작하지 않습니다. ```python # 동기 방식 — 총 3초 소요 import time def fetch_a(): time.sleep(1); return "A" def fetch_b(): time.sleep(1); return "B" def fetch_c(): time.sleep(1); return "C" results = [fetch_a(), fetch_b(), fetch_c()] # 순차 = 3초 ``` 비동기 방식은 기다리는 동안 다른 작업을 실행합니다. 총 **~1초**로 줄어듭니다. --- ## asyncio 기본 문법 ```python import asyncio async def fetch_a(): await asyncio.sleep(1) return "A" async def fetch_b(): await asyncio.sleep(1) return "B" async def main(): a, b = await asyncio.gather(fetch_a(), fetch_b()) print(a, b) # A B (약 1초) asyncio.run(main()) ``` ### 핵심 개념 | 키워드/함수 | 역할 | |---|---| | `async def` | 코루틴 함수 선언 | | `await` | 실행 대기 (이 사이 다른 코루틴 실행 가능) | | `asyncio.gather()` | 여러 코루틴 동시 실행 | | `asyncio.run()` | 이벤트 루프 시작 (진입점) | | `asyncio.create_task()` | 백그라운드 태스크 생성 | --- ## 실전 패턴: 비동기 HTTP 요청 ```python import asyncio import aiohttp async def fetch_url(session, url): async with session.get(url) as resp: return await resp.text() async def main(): urls = [ "https://jsonplaceholder.typicode.com/posts/1", "https://jsonplaceholder.typicode.com/posts/2", "https://jsonplaceholder.typicode.com/posts/3", ] async with aiohttp.ClientSession() as session: results = await asyncio.gather(*[fetch_url(session, u) for u in urls]) for r in results: print(r[:80]) asyncio.run(main()) ``` > `requests`는 동기 전용. 비동기 HTTP에는 **`aiohttp`** 또는 **`httpx`** 사용. --- ## 동기 코드와의 혼용 — run_in_executor ```python import asyncio import requests async def fetch_sync_in_async(url): loop = asyncio.get_event_loop() response = await loop.run_in_executor(None, requests.get, url) return response.json() ``` --- ## 흔한 실수 ```python # ❌ await 없이 코루틴 호출 — 실행 안 됨 result = fetch_a() # ✅ 올바름 result = await fetch_a() # ❌ 이벤트 루프에서 time.sleep 사용 — 전체 루프 차단 async def bad(): time.sleep(1) # ✅ asyncio.sleep 사용 async def good(): await asyncio.sleep(1) ``` --- ## asyncio vs threading vs multiprocessing | | asyncio | threading | multiprocessing | |---|---|---|---| | **적합한 작업** | I/O 바운드 | I/O 바운드 | CPU 바운드 | | **GIL 영향** | 없음 (단일 스레드) | 있음 | 없음 | | **오버헤드** | 낮음 | 중간 | 높음 | > 웹 크롤링, API 호출, DB 쿼리 → **asyncio** > 이미지 처리, ML 연산 → **multiprocessing**
// COMMENTS
Newest First
ON THIS PAGE