In Python, the async
keyword is used to define a coroutine function, which allows for asynchronous programming. Async functions are used to perform tasks concurrently and can be suspended and resumed during execution, allowing other tasks to run in the meantime.
Here’s an example that demonstrates the use of async
in Python:
import asyncio
async def count_down(name, count):
while count > 0:
print(f'{name}: {count}')
await asyncio.sleep(1) # Await the sleep coroutine
count -= 1
async def main():
# Create two tasks that will run concurrently
task1 = asyncio.create_task(count_down('Task 1', 5))
task2 = asyncio.create_task(count_down('Task 2', 3))
# Wait for both tasks to complete
await asyncio.gather(task1, task2)
asyncio.run(main())
Code language: Python (python)
In this example, we define an async
function called count_down
that takes a name and a count as parameters. It prints the count value and then suspends execution for one second using the await asyncio.sleep(1)
statement. This allows other tasks to run during the sleep period. The count is decremented in each iteration until it reaches zero.
The main
function creates two tasks using asyncio.create_task()
to run the count_down
coroutine concurrently. The asyncio.gather()
function is used to wait for both tasks to complete before the program exits.
By using async
and await
, we can write asynchronous code that appears synchronous and allows for better utilization of system resources when dealing with I/O-bound tasks or parallel processing.
Read More;
- How to do Single Line for Loop in Python
- What is Len() in Python With Example
- What does V mean in Python?
- What are Membership Operators in Python With Example?
- What is Encapsulation in Python With Example
- Python Joblib Parallel For Loop Example
- How to Derive in Python
- What is ‘Self’ in Python With Example
- What is Keyword Argument in Python with Example?
- What is Inheritance With Examples in Python
- What is Token in Python With Example
- How to Use def in Python With Example