[Python]비동기 I/O 처리 (AsyncIO)
비동기 I/O 처리를 위한 라이브러리(AsyncIO)를 알아보자
# AsyncIO : 비동기 I/O Coroutine 작업, NonBlocking 비동기 처리
# Blocking I/O : 호출된 함수가 자신의 작업이 완료 될때가지 제어권을 가지고 있음
# NonBlocking I/O : 호출된 함수가(서브루틴) 호출한 함수(메인루틴)에 제어권 즉시 반환
import asyncio
import threading
import timeit
from concurrent.futures import ThreadPoolExecutor
from urllib.request import urlopen
from bs4 import BeautifulSoup
# 실행 시작시간
start = timeit.default_timer()
# 수집할 사이트 URL
urls = ['https://www.jigi.net', 'https://www.naver.com', 'https://www.daum.net', 'https://tistory.com',
'https://front.homeplus.co.kr']
async def fetch_site(url, executor):
# Thread 정보출력
print(f'Thread Name : {threading.current_thread().getName()} Start, {url}')
# 실행
response = await loop.run_in_executor(executor, urlopen, url)
soup = BeautifulSoup(response.read(), 'html.parser')
#전체 페이지 소스 확인
# print(soup.prettify())
# 타이틀만 가져옴
result = soup.title
print(f'Thread Name : {threading.current_thread().getName()} Done, {url}')
# 결과 반환
return result
async def my_func():
# 쓰레드풀 생성
executor = ThreadPoolExecutor(max_workers=10)
# future 객체 모아서 gather에서 실행
futures = [asyncio.ensure_future(fetch_site(url, executor)) for url in urls]
# 결과 취합 (await : 결과가 모두 나올 때까지 기다림)
result = await asyncio.gather(*futures)
print()
print('Result : ', result)
if __name__ == '__main__':
# loop 초기화
loop = asyncio.get_event_loop()
# 작업이 완료될 때까지 대기
loop.run_until_complete(my_func())
# 수행시간
duration = timeit.default_timer() - start
# 수행시간 출력
print()
print(f'수행에 걸린 시간 : {duration}')
"""
Thread Name : MainThread Start, https://www.jigi.net
Thread Name : MainThread Start, https://www.naver.com
Thread Name : MainThread Start, https://www.daum.net
Thread Name : MainThread Start, https://tistory.com
Thread Name : MainThread Start, https://front.homeplus.co.kr
Thread Name : MainThread Done, https://front.homeplus.co.kr
Thread Name : MainThread Done, https://www.naver.com
Thread Name : MainThread Done, https://tistory.com
Thread Name : MainThread Done, https://www.daum.net
Thread Name : MainThread Done, https://www.jigi.net
Result : [<title>지기닷넷 – 꿈을 실현합니다.</title>, <title>NAVER</title>, <title>Daum</title>, <title>TISTORY</title>, <title>홈플러스 | 위풍당당 프로젝트</title>]
수행에 걸린 시간 : 0.715701292
"""
최신 댓글