The Python
asyncio
module
provides a framework for writing
asynchronous programs
using
coroutines
, event loops, and tasks.
It allows you to write
concurrent
code using the
async
and
await
keywords, making it easier to manage
I/O-bound tasks
in your code.
Here’s a quick example:
Python
Key Features
input/output (I/O)
tasks
Manages event loops for scheduling and executing tasks
Allows task synchronization with locks, events, and semaphores
Frequently Used Classes and Functions
asyncio.as_completed()
Function
Returns an iterator that yields awaitables as they complete
asyncio.Lock
Class
Provides a lock object for coroutines
>>>
async
def
worker
(
id
,
lock
):
...
async
with
lock
:
...
print
(
f
"Lock acquired by worker:
{
id
}
"
)
...
await
asyncio
.
sleep
(
1
)
...
print
(
f
"Lock released by worker:
{
id
}
"
)
>>>
async
def
main
():
...
lock
=
asyncio
.
Lock
()
...
await
asyncio
.
gather
(
worker
(
"1"
,
lock
),
worker
(
"2"
,
lock
))
>>>
asyncio
.
run
(
main
())
Lock acquired by worker: 1
Lock released by worker: 1
Lock acquired by worker: 2
Lock released by worker: 2
Managing concurrent I/O-bound operations efficiently
Building network clients and servers
Coordinating tasks with synchronization primitives
Running background tasks while maintaining responsive applications