Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
asyncioAsynchronous programming represents a paradigm shift in how high-concurrency network servers and distributed clients are built in Python. The standard library module asyncio introduces Cooperative Multitasking on a single thread via an Event Loop, allowing applications to handle tens of thousands of concurrent network sockets with minimal memory overhead.
In multithreading, the operating system kernel forcibly pauses and resumes threads via preemption, incurring hardware context-switching overhead and requiring complex mutex locks.
In cooperative multitasking with asyncio, tasks run on a single thread and explicitly yield control back to the event loop only when waiting for an I/O operation (such as waiting for bytes from a network socket):
asyncio coroutine is a lightweight heap object consuming only ~1KB. A single process can maintain 100,000+ active coroutines effortlessly.await points, you cannot have thread-switching collisions between statements.At the center of asyncio is the Event Loop, an infinite dispatching loop backed by kernel I/O multiplexing primitives:
CPython delegates network socket polling to the fastest OS-native multiplexer available:
epoll (via AsyncioSelectorEventLoop)kqueueIOCP via ProactorEventLoop, default in Python 3.8+)time.sleep(), synchronous file I/O, or requests.get()) freezes the entire thread. While the thread is blocked, all other coroutines and network sockets are completely starved of execution.asyncio.run()Prior to Python 3.7, initializing an event loop required verbose, error-prone boilerplate:
asyncio.run() Handles Automatically:| Metric | Multithreading | asyncio Cooperative |
|---|---|---|
| Execution Model | Preemptive (OS kernel manages) | Cooperative (Developer manages via await) |
| Thread Count | Multiple native OS threads | Single thread (by default) |
| Context Switch Overhead | Kernel register/stack swaps | Frame pointer updates on heap (~zero overhead) |
| Memory per Unit | 2MB – 8MB per thread | ~1KB per coroutine |
| Synchronization | Heavy mutex locks required | No race conditions between statements |
| Best Used For | Moderate I/O, blocking C-libraries | Massive concurrent sockets (WebSockets, microservices) |
Executing synchronous blocking calls like time.sleep(5) or requests.get() inside a coroutine freezes the entire event loop, starving all other concurrent coroutines. Use asyncio.sleep() and aiohttp.
Asyncio is designed for cooperative I/O-bound concurrency. Offload heavy CPU calculations to a process pool using loop.run_in_executor().
Write two async coroutines running concurrently on the asyncio event loop using asyncio.gather().
How does cooperative multitasking in asyncio differ from preemptive multithreading? A. asyncio runs each function on a separate physical computer. B. In asyncio, coroutines explicitly surrender execution to the event loop at await expressions rather than being preemptively interrupted by the OS kernel. C. asyncio requires administrative privileges. D. Multithreading cannot run network queries.
await points, whereas preemptive multithreading allows the OS scheduler to interrupt and swap threads at any CPU instruction.What occurs if a developer executes a blocking synchronous call like time.sleep(5) inside an asyncio coroutine? A. The event loop moves that coroutine to a separate thread automatically. B. The entire single-threaded event loop freezes for 5 seconds, starving all other concurrent coroutines and network connections. C. A RuntimeWarning is logged, and the function executes asynchronously. D. Only the caller is paused.
asyncio executes on a single thread, any synchronous blocking system call prevents the event loop from running, halting all other scheduled tasks for the duration of the call.What low-level operating system multiplexing mechanism does asyncio use by default on Windows starting in Python 3.8? A. POSIX pthreads B. I/O Completion Ports (IOCP via ProactorEventLoop) C. Win32 Registry handles D. Direct3D pipelines
ProactorEventLoop (backed by Windows I/O Completion Ports / IOCP) the default event loop implementation on Windows for high-performance non-blocking I/O.What is the recommended modern entry point for executing a top-level coroutine in Python 3.7+? A. asyncio.get_event_loop().run_forever() B. asyncio.run(main()) C. asyncio.execute(main) D. main.start()
asyncio.run(coroutine) was introduced in Python 3.7 as the standard high-level API to manage event loop creation, execution, task cancellation, and loop closure.Why can an asyncio application handle 50,000 concurrent network connections with far less RAM than a multithreaded application? A. Sockets in asyncio do not use memory. B. Each coroutine is a lightweight in-memory frame object (~1KB), whereas each thread requires a large operating system stack (typically 2MB–8MB). C. asyncio compiles to WebAssembly. D. Coroutines bypass the Linux kernel.
In the next lesson, we will continue your advanced Python journey with Async and Await Syntax (8: Asynchronous Programming (Asyncio)).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Project: Parallel File Processor | Async and Await Syntax |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.