Python’s asyncio helps one thread make progress on multiple I/O-bound tasks by switching between coroutines when they reach await. It is useful for network clients, servers, and other work that spends time waiting; it does not automatically make CPU-heavy synchronous code run in parallel. The Python documentation describes asyncio as “a library to write concurrent code using the async/await syntax.”
How asyncio works
An async def function defines a coroutine function. Calling it creates a coroutine object; it does not run the function to completion. A coroutine must be awaited by another coroutine or scheduled as a task. The event loop runs ready tasks and can switch to other work when the current task suspends at an await point.
This is cooperative concurrency: a task runs until it awaits something that yields control. If it calls a blocking synchronous function, the event-loop thread remains occupied until that call returns, and other tasks on that loop cannot run meanwhile. Asyncio therefore fits waiting-heavy I/O, not CPU-intensive synchronous computation by itself.
A first program
The following example uses APIs available in Python 3.11 and later. It runs two waits concurrently; the elapsed time is approximately the duration of the longer wait, rather than their sum, subject to normal scheduling and system variation.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import asyncio
async def greet(name: str) -> None:
print(f"Starting {name}")
await asyncio.sleep(1)
print(f"Finished {name}")
async def main() -> None:
await asyncio.gather(greet("Ari"), greet("Sam"))
if __name__ == "__main__":
asyncio.run(main())
asyncio.sleep() suspends the current task without blocking the event-loop thread. By contrast, adding a synchronous blocking sleep or a slow blocking network call inside greet would stop the loop from advancing other tasks during that call.
Decide whether asyncio fits
| Workload | Typical fit | Reason |
|---|---|---|
| Many network requests or other asynchronous I/O waits | Good fit | Tasks can yield while awaiting I/O, allowing the event loop to run other ready tasks. |
| CPU-heavy calculations in ordinary synchronous Python code | Not by itself | Such code does not yield automatically and can block the event-loop thread. |
| A small script or application with no concurrent waits | Often unnecessary | Async syntax and lifecycle management add complexity without a clear concurrency need. |
| Framework or library code needing custom loop mechanics | Possibly | Low-level loop, future, and transport/protocol APIs provide control, but most application code should start with high-level APIs. |
Asyncio is not a universal speed upgrade. Its benefit depends on the workload and on using non-blocking operations throughout the event-loop path.
Run an async program
For a normal standalone program, define an async entry point and pass its coroutine to asyncio.run(). It manages the event loop for that top-level run and is the ordinary starting point recommended by the asyncio documentation.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import asyncio
async def main() -> None:
print("Hello from asyncio")
asyncio.run(main())
Do not call asyncio.run() from code already running inside an event loop. In environments that provide their own loop, such as some interactive shells or application frameworks, use that environment’s supported way to await the coroutine rather than trying to start a second top-level loop.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Run related coroutines as tasks
Use tasks when work should proceed concurrently while the current coroutine continues. In Python 3.11 and later, asyncio.TaskGroup is a structured-concurrency option: the group owns its child tasks, waits for them when its context exits, and provides a clear boundary for their lifetime.
import asyncio
async def fetch_label(label: str) -> str:
await asyncio.sleep(0.2)
return f"result: {label}"
async def main() -> None:
async with asyncio.TaskGroup() as group:
first = group.create_task(fetch_label("one"))
second = group.create_task(fetch_label("two"))
print(first.result())
print(second.result())
asyncio.run(main())
When a child task in a TaskGroup fails with an exception other than cancellation, the group cancels the remaining tasks, waits for them, and reports failures using an exception group. This makes related work fail as a unit instead of leaving sibling tasks running unnoticed. Check the documentation for the Python version you deploy: task-group behavior and available APIs are version-sensitive.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Task results and exceptions
A task’s result is available after it finishes; calling result() before completion raises an error. If the task failed, retrieving its result raises the task’s exception. Awaiting a task is often the clearest way to receive its result or exception. Keep references to tasks whose lifetime you manage, and ensure they are awaited or otherwise supervised; untracked background tasks can finish after their owner has moved on.
Cancellation and cleanup
Cancellation is delivered to a coroutine as asyncio.CancelledError at a suspension point. Use try/finally for cleanup such as closing a connection or releasing a resource, and generally allow cancellation to propagate after cleanup rather than swallowing it.
async def work() -> None:
resource = await acquire_resource()
try:
await use_resource(resource)
finally:
await resource.close()
The names in this snippet illustrate the cleanup pattern; acquire_resource, use_resource, and close depend on the library providing the resource.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Use asyncio’s high-level APIs
The standard library groups practical async tools into several families. Prefer these APIs for application code before reaching for event-loop internals.
- Network I/O: streams provide high-level building blocks for reading and writing network data asynchronously.
- Queues:
asyncio.Queuecan pass work between producer and consumer tasks without blocking the event-loop thread. - Synchronization: asyncio locks, events, conditions, and semaphores coordinate tasks that share state or limit concurrent work.
- Subprocesses: asyncio subprocess APIs let a coroutine interact with a child process asynchronously.
- Timeouts and exceptions: the library includes timeout and exception facilities for bounding waits and handling failures.
Lower-level event loops, futures, transports, and protocols are mainly useful when building frameworks or libraries that need finer control. They are not the default starting point for most application developers.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Debug blocking and scheduling problems
If tasks that should overlap instead run one at a time, look for synchronous blocking work on the event-loop thread. Common examples include a blocking HTTP client, file operation, or long computation called directly from an async function. Use an async-compatible library when available; for CPU-bound or blocking work, choose an execution strategy suited to that work rather than expecting await to make it non-blocking.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Enable asyncio debug mode during development to expose issues such as slow callbacks. The development guide also documents how to schedule callbacks safely from another OS thread: use the event loop’s thread-safe scheduling APIs rather than manipulating loop-bound objects directly from that thread. For example, loop.call_soon_threadsafe(callback, arg) schedules a callback onto the loop thread.
Common errors and fixes
- “Coroutine was never awaited”: calling an
async deffunction creates a coroutine but does not execute it. Await it or schedule it as a task. - “asyncio.run() cannot be called from a running event loop”: the environment already owns a loop. Await the coroutine through the environment’s supported interface.
- Other tasks freeze during a slow operation: a synchronous blocking call is likely running on the loop thread. Replace it with a non-blocking alternative or move the blocking work to an appropriate executor or process strategy.
- Child task errors appear late or are missed: tasks may not have an owner or be awaited. Use a
TaskGroupfor related work, or explicitly retain, await, and supervise separately managed tasks. - Work is scheduled from a different OS thread: use a thread-safe loop scheduling API such as
call_soon_threadsafe().
Version and platform considerations
The code examples above target Python 3.11 or later because they use TaskGroup. The official documentation includes versioned references; check the documentation matching the interpreter you deploy, particularly for newer APIs and evolving task behavior. The Python 3.16.0a0 documentation is prerelease documentation, not evidence of a stable release. Asyncio support can also vary by platform for some APIs, so verify platform-specific requirements for the network, subprocess, or loop feature you intend to use.
Or skip the browser setup
If your asyncio project needs website screenshots, ScreenshotNeo offers a single GET request rather than a browser session to install and manage. Before capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be disabled. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
For example, from an asyncio application you can make the GET request with an async HTTP client; this runnable synchronous cURL call shows the API request itself. See the ScreenshotNeo API documentation for parameters and response handling.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo offers 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo, or sign up for the free plan.
Frequently Asked Questions
Can asyncio use multiple CPU cores by itself?
No. Asyncio coordinates tasks on an event loop; CPU-heavy synchronous code does not become parallel merely because it is called from an async function.
What should I use instead of asyncio for a CPU-bound workload?
Choose a concurrency or parallel execution approach suited to CPU work, such as a process-based strategy, rather than relying on cooperative I/O scheduling.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.

