Python asyncio Module
asyncio is a module in the Python standard library for writing asynchronous I/O code.
asyncio provides an efficient way to handle concurrent tasks, especially suited to I/O-bound operations such as network requests and file reads and writes.
By using asyncio, you can handle multiple tasks concurrently in a single thread without using multiple threads or processes.
Why do we need asyncio?
In traditional synchronous programming, when a task has to wait for an I/O operation (such as a network request) to complete, the program blocks until the operation finishes. This makes the program inefficient, especially when many I/O operations must be handled.
asyncio By introducing an asynchronous programming model, a program can keep executing other tasks while waiting for I/O operations, improving concurrency and efficiency.
Imagine you are running a restaurant:
asyncio is the standard library Python provides for this smart working pattern. It lets you write single-threaded concurrent code, especially suited to I/O-bound scenarios such as web crawlers, web servers and microservices.
Its core is the event loop, coroutines and tasks.
Core concepts of asyncio
1. Coroutine
A coroutine is asyncio 's core concepts. It is a special function that can pause during execution and resume later. Coroutines are defined with the async def keyword and pause execution with the await keyword, waiting for an asynchronous operation to complete.
Example
import
asyncio
async
def
say_hello
(
)
:
(
"Hello"
)
await asyncio.
sleep
(
1
)
(
"World"
)
2. Event loop
The event loop is asyncio 's core component and is responsible for scheduling and executing coroutines. It continually checks whether any task needs to run and invokes the corresponding callback when a task completes.
Example
async
def
main
(
)
:
await say_hello
(
)
asyncio.
run
(
main
(
)
)
3. Task
A task is a wrapper around a coroutine, representing a coroutine that is running or about to run. You can use the asyncio.create_task() function to create a task and add it to the event loop.
Example
async
def
main
(
)
:
task
=
asyncio.
create_task
(
say_hello
(
)
)
await task
4. Future
Future is an object representing the result of an asynchronous operation. It is usually used by low-level APIs to represent an operation that has not completed yet. You can wait for await with the keyword to wait for Future to complete.
Example
async
def
main
(
)
:
future
=
asyncio.
Future
(
)
await future
Basic usage and code examples
Let's understand these concepts through a classic example that concurrently fetches several URLs.
Suppose we need to fetch the content of three different URLs. The synchronous approach runs sequentially, and the total time is the sum of the three request times. Using asyncio, we can issue all three requests at the same time, and the total time is close to the slowest single request.
Synchronous version (for comparison)
Example
import
time
import
requests
def
fetch_url
(
url
)
:
"""Simulate a time-consuming network request (synchronous version)"""
(
f
"Starting fetch: {url}"
)
time
.
sleep
(
2
)
Simulate a 2-second network delay
(
f
"Finished fetch: {url}"
)
return
f
"Data from {url}"
def
main_sync
(
)
:
urls
=
[
'https://example.
com
/
1
'
,
'https://example.
com
/
2
'
,
'https://example.
com
/
3
'
]
results
=
[
]
start
=
time
.
time
(
)
for
url
in
urls:
result
=
fetch_url
(
url
)
Must wait for the previous one to finish before starting the next
results.
append
(
result
)
end
=
time
.
time
(
)
(
f
"Total time for the synchronous version: {end - start:.2f} seconds"
)
(
f
"Results: {results}"
)
if
name
==
"main"
:
main_sync
(
)
Expected output:
开始获取: https://example.com/1
完成获取: https://example.com/1
开始获取: https://example.com/2
完成获取: https://example.com/2
开始获取: https://example.com/3
完成获取: https://example.com/3
同步版本总耗时: 6.00 秒
结果: [‘来自 https://example.com/1 的数据‘, ‘来自 https://example.com/2 的数据‘, ‘来自 https://example.com/2 的数据‘]
It took about 6 seconds in total.
Asynchronous version (using asyncio)
We need to use the aiohttp library instead of requests for asynchronous HTTP requests. Install it first:pip install aiohttp。
Example
import
asyncio
import
aiohttp
import
time
async
def
fetch_url_async
(
session
,
url
)
:
"""Simulate a time-consuming network request (asynchronous version)"""
(
f
"Starting async fetch: {url}"
)
Note: here we use aiohttp's asynchronous get method and await it
async
with
session.
get
(
url
)
as
response:
Simulate that processing the response also takes time
await asyncio.
sleep
(
2
)
Use asyncio.sleep to simulate the I/O wait; it does not block the thread
text
=
await response.
text
(
)
(
f
"Finished async fetch: {url}"
)
return
f
"Data from {url} (length: {len(text)})"
async
def
main_async
(
)
:
urls
=
[
'https://httpbin.
org
/get'
,
'https://httpbin.
org
/delay/
1
'
,
'https://httpbin.
org
/headers'
]
async
with
aiohttp.
ClientSession
(
)
as
session:
Create an asynchronous HTTP session
Create a task for each URL
tasks
=
[
]
for
url
in
urls:
create_task adds the coroutine to the event loop and starts scheduling immediately
task
=
asyncio.
create_task
(
fetch_url_async
(
session
,
url
)
)
tasks.
append
(
task
)
(
"All tasks created, starting concurrent execution..."
)
Use asyncio.gather to run all tasks concurrently and wait for all of them to finish
gather returns a list of results in the same order as the tasks passed in
results
=
await asyncio.
gather
(
*tasks
)
return
results
if
name
==
"main"
:
start
=
time
.
time
(
)
asyncio.run() is a convenient way to start the event loop and run a top-level coroutine
final_results
=
asyncio.
run
(
main_async
(
)
)
end
=
time
.
time
(
)
(
f
"\nTotal time for the asynchronous version: {end - start:.2f} seconds"
)
for
res
in
final_results:
(
res
)
Expected output:
所有任务已创建,开始并发执行...
开始异步获取: https://httpbin.org/get
开始异步获取: https://httpbin.org/delay/1
开始异步获取: https://httpbin.org/headers
(大约 2 秒后,所有请求几乎同时完成)
完成异步获取: https://httpbin.org/headers
完成异步获取: https://httpbin.org/get
完成异步获取: https://httpbin.org/delay/1
异步版本总耗时: 2.10 秒 # 注意!总耗时远小于 6 秒
来自 https://httpbin.org/get 的数据 (长度: 274)
来自 https://httpbin.org/delay/1 的数据 (长度: 392)
来自 https://httpbin.org/headers 的数据 (长度: 177)
Code Analysis:
async def: defines the coroutine functionfetch_url_asyncandmain_async。await: Infetch_url_async, weawait session.get()andawait response.text(), which tells the event loop: "this network request takes time, go run other ready tasks first".asyncio.create_task(): Setfetch_url_asyncWrap the coroutine intoTaskso that it is scheduled by the event loop, achieving concurrency.asyncio.gather(*tasks): a very useful function that runs all the passed coroutines/tasks concurrently, waits for all of them to finish, and finally collects all results.asyncio.run(main_async()): the recommended approach in Python 3.7+; it creates the event loop, runs the coroutine and closes the loop.
Key functions and parameters
The table below lists asyncio several of the most commonly used high-level functions:
| function | Main purpose | Common parameters |
|---|---|---|
asyncio.run(coro, *, debug=False) |
Run a top-level coroutine and manage the event loop's lifetime. This is the program's main entry point. | coro: the coroutine object to run. |
debug: set to True to enable the event loop's debug mode. |
||
asyncio.create_task(coro, *, name=None) |
Wrap a coroutine into a Task object and queue it in the event loop for scheduling. This is the main way to achieve concurrency. | coro: the coroutine object to wrap. |
name: (Python 3.8+) assign a name to the task for easier debugging. |
||
asyncio.gather(*aws, return_exceptions=False) |
Concurrently runmultiple asynchronous tasks (aws accepts coroutines, tasks, etc.), wait for all of them to finish, and return a list of results. |
*aws: variadic; pass multiple asynchronous objects. |
return_exceptions: defaults to False; any exception raised by a task propagates immediately to gather 's caller. When set to True , exceptions are returned as part of the results. |
||
asyncio.sleep(delay, result=None) |
Asynchronouslysleep for the specified number of seconds. This is the key difference from time.sleep(blocking). |
delay: the number of seconds to sleep. |
result: the value returned after sleeping. |
||
asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED) |
Run tasks concurrently and wait until the specified condition is met. Returns two sets, (done, pending), namely the completed and the pending tasks. |
aws: a collection of asynchronous objects. |
`timeout`: 超时时间(秒)。
`return_when`: 决定何时返回,可选:`FIRST_COMPLETED`(第一个完成)、`FIRST_EXCEPTION`(第一个异常)、`ALL_COMPLETED`(全部完成,默认)。 |
| asyncio.to_thread(func, /, *args, **kwargs) | (Python 3.9+) runs an ordinary, possibly blocking synchronous function in a separate thread and returns an awaitable await coroutine. Used for CPU-intensive or blocking I/O. | func: the synchronous function to run in the thread.
*args, **kwargs: the arguments passed to the function. |
Visual understanding: asynchronous task scheduling flow

Diagram explanation: this flowchart shows how the event loop works like a dispatcher. It maintains a task queue; when a task reaches await(for example, waiting for a network response), it is suspended and the event loop immediately picks the next runnable (ready) task from the queue to execute. When the suspended task's I/O operation completes, the event loop is notified, marks the task as ready again, and resumes it at some later point. In this way the CPU is fully utilized during I/O waits to execute other tasks, achieving concurrency within a single thread.
Basic usage of asyncio
1. Run a coroutine
To run a coroutine, you can use the asyncio.run() function. It creates an event loop and runs the specified coroutine.
Example
import
asyncio
async
def
main
(
)
:
(
"Start"
)
await asyncio.
sleep
(
1
)
(
"End"
)
asyncio.
run
(
main
(
)
)
2. Execute multiple tasks concurrently
You can use the asyncio.gather() function to execute multiple coroutines concurrently and wait for all of them to finish.
Example
import
asyncio
async
def
task1
(
)
:
(
"Task 1 started"
)
await asyncio.
sleep
(
1
)
(
"Task 1 finished"
)
async
def
task2
(
)
:
(
"Task 2 started"
)
await asyncio.
sleep
(
2
)
(
"Task 2 finished"
)
async
def
main
(
)
:
await asyncio.
gather
(
task1
(
)
,
task2
(
)
)
asyncio.
run
(
main
(
)
)
3. Timeout control
You can use the asyncio.wait_for() The function sets a timeout for a coroutine. If the coroutine does not finish within the specified time, a asyncio.TimeoutError exception.
Example
import
asyncio
async
def
long_task
(
)
:
await asyncio.
sleep
(
10
)
(
"Task finished"
)
async
def
main
(
)
:
try
:
await asyncio.
wait_for
(
long_task
(
)
,
timeout
=
5
)
except
asyncio.
TimeoutError
:
(
"Task timed out"
)
asyncio.
run
(
main
(
)
)
Application scenarios for asyncio
asyncio It is especially suitable for the following scenarios:
- Network requests: such as HTTP requests and WebSocket communication.
- File I/O: such as asynchronous file reads and writes.
- Database operations: such as asynchronous database access.
- Real-time data processing: such as real-time message queue processing.
Common classes, methods and functions
1. Core functions
| Method/function | Description | Example |
|---|---|---|
asyncio.run(coro) |
Run an asynchronous main function (Python 3.7+) | asyncio.run(main()) |
asyncio.create_task(coro) |
Create a task and add it to the event loop | task = asyncio.create_task(fetch_data()) |
asyncio.gather(*coros) |
Run multiple coroutines concurrently | await asyncio.gather(task1, task2) |
asyncio.sleep(delay) |
Asynchronous wait (non-blocking) | await asyncio.sleep(1) |
asyncio.wait(coros) |
Control how tasks are awaited as they complete | done, pending = await asyncio.wait([task1, task2]) |
2. Event loop
| Method | Description | Example |
|---|---|---|
loop.run_until_complete(future) |
Run until the task completes | loop.run_until_complete(main()) |
loop.run_forever() |
Run the event loop forever | loop.run_forever() |
loop.stop() |
Stop the event loop | loop.stop() |
loop.close() |
Close the event loop | loop.close() |
loop.call_soon(callback) |
Schedule a callback for immediate execution | loop.call_soon(print, "Hello") |
loop.call_later(delay, callback) |
Execute a callback after a delay | loop.call_later(5, callback) |
3. Coroutines and tasks
| Method/decorator | Description | Example |
|---|---|---|
@asyncio.coroutine |
Coroutine decorator (legacy, Python 3.4-3.7) | @asyncio.coroutine |
def old_coro(): |
||
async def |
Define a coroutine (Python 3.5+) | async def fetch(): |
task.cancel() |
Cancel a task | task.cancel() |
task.done() |
Check whether a task is done | if task.done(): |
task.result() |
Get the task result (task must be done) | data = task.result() |
4. Synchronization primitives (similar tothreading)
| class | Description | Example |
|---|---|---|
asyncio.Lock() |
Asynchronous mutex lock | lock = asyncio.Lock() |
async with lock: |
||
asyncio.Event() |
Event notification | event = asyncio.Event() |
await event.wait() |
||
asyncio.Queue() |
Asynchronous queue | queue = asyncio.Queue() |
await queue.put(item) |
||
asyncio.Semaphore() |
Semaphore | sem = asyncio.Semaphore(5) |
async with sem: |
5. Networking and subprocesses
| Method/class | Description | Example |
|---|---|---|
asyncio.open_connection() |
Establish a TCP connection | reader, writer = await asyncio.open_connection('host', 80) |
asyncio.start_server() |
Create a TCP server | server = await asyncio.start_server(handle, '0.0.0.0', 8888) |
asyncio.create_subprocess_exec() |
Create a subprocess | proc = await asyncio.create_subprocess_exec('ls') |
6. Utilities
| Method | Description | Example |
|---|---|---|
asyncio.current_task() |
Get the current task | task = asyncio.current_task() |
asyncio.all_tasks() |
Get all tasks | tasks = asyncio.all_tasks() |
asyncio.shield(coro) |
Shield a task from cancellation | await asyncio.shield(critical_task) |
asyncio.wait_for(coro, timeout) |
Wait with a timeout | try: await asyncio.wait_for(task, 5) |
Example
- Basic coroutine example
Example
import
asyncio
async
def
hello
(
)
:
(
"Hello"
)
await asyncio.
sleep
(
1
)
(
"World"
)
asyncio.
run
(
hello
(
)
)
Python 3.7+
- Execute tasks concurrently
Example
async
def
fetch
(
url
)
:
(
f
"Fetching {url}"
)
await asyncio.
sleep
(
2
)
return
f
"Data from {url}"
async
def
main
(
)
:
results
=
await asyncio.
gather
(
fetch
(
"url1.com"
)
,
fetch
(
"url2.com"
)
)
(
results
)
asyncio.
run
(
main
(
)
)
- Use an asynchronous queue
Example
async
def
producer
(
queue
)
:
for
i
in
range
(
5
)
:
await queue.
put
(
i
)
await asyncio.
sleep
(
0.1
)
async
def
consumer
(
queue
)
:
while
True
:
item
=
await queue.
get
(
)
(
f
"Consumed {item}"
)
queue.
task_done
(
)
async
def
main
(
)
:
queue
=
asyncio.
Queue
(
)
await asyncio.
gather
(
producer
(
queue
)
,
consumer
(
queue
)
)
Notes
-
Python version: some features require Python 3.7+ (such as
asyncio.run())。 -
Blocking operations: avoid synchronous blocking code in coroutines (such as
time.sleep())。 -
Debugging: set the
PYTHONASYNCIODEBUG=1environment variable to enable debug mode. -
Cancel a task: a cancelled task raises
CancelledErrorand must be handled properly.