Python 비동기 프로그래밍 시작하기
KDnuggets
|
|
💼 비즈니스
#async
#i/o
#python
#tip
#비동기
#프로그래밍
원문 출처: KDnuggets · Genesis Park에서 요약 및 분석
요약
비동기 프로그래밍을 마스터하여 파이썬 애플리케이션의 속도를 높이는 방법을 배울 수 있습니다. 이 가이드는 입출력(I/O) 병목 현상을 효율적으로 관리하고 실제 사례를 통해 더 빠른 앱을 구축하는 기술을 제공합니다.
본문
Getting Started with Python Async Programming Build faster Python applications by mastering async programming and learning how to handle I/O bound workloads efficiently with real world examples. Image by Author # Introduction Most Python applications spend significant time waiting on APIs, databases, file systems, and network services. Async programming allows a program to pause while waiting for I/O operations and continue executing other tasks instead of blocking. In this tutorial, you will learn the fundamentals of async programming in Python using clear code examples. We will compare synchronous and asynchronous execution, explain how the event loop works, and apply async patterns to real-world scenarios such as concurrent API requests and background tasks. By the end of this guide, you will understand when async programming is useful, how to use async and await correctly, and how to write scalable and reliable async Python code. # Defining Async Programming in Python Async programming allows a program to pause execution while waiting for an operation to complete and continue executing other tasks in the meantime. Core building blocks include: async def for defining coroutinesawait for non-blocking waits- The event loop for task scheduling Note: Async programming improves throughput, not raw computation speed. # Understanding the Async Event Loop in Python The event loop is responsible for managing and executing asynchronous tasks. Key responsibilities include: - Tracking paused and ready tasks - Switching execution when tasks await I/O - Coordinating concurrency without threads Python uses the asyncio library as its standard async runtime. # Comparing Sequential vs. Async Execution in Python This section demonstrates how blocking sequential code compares to asynchronous concurrent execution and how async reduces total waiting time for I/O-bound tasks. // Examining a Sequential Blocking Example Sequential execution runs tasks one after another. If a task performs a blocking operation, the entire program waits until that operation completes. This approach is simple but inefficient for I/O-bound workloads where waiting dominates execution time. This function simulates a blocking task. The call to time.sleep pauses the entire program for the specified number of seconds. import time def download_file(name, seconds): print(f"Starting {name}") time.sleep(seconds) print(f"Finished {name}") The timer starts before the function calls and stops after all three calls complete. Each function runs only after the previous one finishes. start = time.perf_counter() download_file("file-1", 2) download_file("file-2", 2) download_file("file-3", 2) end = time.perf_counter() print(f"[TOTAL SYNC] took {end - start:.4f} seconds") Output: file-1 starts and blocks the program for two secondsfile-2 starts only afterfile-1 finishesfile-3 starts only afterfile-2 finishes Total runtime is the sum of all delays, approximately six seconds. Starting file-1 Finished file-1 Starting file-2 Finished file-2 Starting file-3 Finished file-3 [TOTAL SYNC] took 6.0009 seconds // Examining an Asynchronous Concurrent Example Asynchronous execution allows tasks to run concurrently. When a task reaches an awaited I/O operation, it pauses and allows other tasks to continue. This overlapping of waiting time significantly improves throughput. This async function defines a coroutine. The await asyncio.sleep call pauses only the current task, not the entire program. import asyncio import time async def download_file(name, seconds): print(f"Starting {name}") await asyncio.sleep(seconds) print(f"Finished {name}") asyncio.gather schedules all three coroutines to run concurrently on the event loop. async def main(): start = time.perf_counter() await asyncio.gather( download_file("file-1", 2), download_file("file-2", 2), download_file("file-3", 2), ) end = time.perf_counter() print(f"[TOTAL ASYNC] took {end - start:.4f} seconds") This starts the event loop and executes the async program. asyncio.run(main()) Output: - All three tasks start almost at the same time - Each task waits independently for two seconds - While one task is waiting, others continue executing - Total runtime is close to the longest single delay, approximately two seconds Starting file-1 Starting file-2 Starting file-3 Finished file-1 Finished file-2 Finished file-3 [TOTAL ASYNC] took 2.0005 seconds # Exploring How Await Works in Python Async Code The await keyword tells Python that a coroutine may pause and allow other tasks to run. Incorrect usage: async def task(): asyncio.sleep(1) Correct usage: async def task(): await asyncio.sleep(1) Failing to use await prevents concurrency and may cause runtime warnings. # Running Multiple Async Tasks Using asyncio.gather asyncio.gather allows multiple coroutines to run concurrently and collects their results once all tasks have completed. It is commonly used when several independent async operations can be executed in parallel. The job coroutine
Genesis Park 편집팀이 AI를 활용하여 작성한 분석입니다. 원문은 출처 링크를 통해 확인할 수 있습니다.
공유