I/O 작업
블로킹 I/O는
즉, 블로킹 I/O 호출은
다음은 파이썬에서 파일을 읽는 블로킹 I/O 예시입니다:
with open('example.txt', 'r') as file:
data = file.read() # 이 호출은 파일이 모두 읽힐 때까지 블로킹됨
print("File reading is done.")
위 코드에서 file.read()는 파일의 모든 내용을 읽을 때까지 현재 스레드를 블로킹합니다. 파일 읽기가 완료되기 전까지는 print("File reading is done.") 라인이 실행되지 않습니다.
이벤트 루프나 콜백, 비동기 프로그래밍을 통해 주로 구현파이썬에서는 asyncio 모듈을 사용하여 비동기 I/O를 구현할 수 있습니다:
import asyncio
async def read_file_async(filename):
loop = asyncio.get_event_loop()
with open(filename, 'r') as file:
data = await loop.run_in_executor(None, file.read) # 비동기로 파일 읽기
print("File reading is done.")
return data
asyncio.run(read_file_async('example.txt'))
await 키워드를 사용하여 파일을 비동기로 읽습니다.