Junior — Middle
Can you give an example of using asynchronous mechanisms in code?
sobes.tech AI
Answer from AI
Asynchronous programming in Python is implemented using the keywords async and await, as well as the asyncio module. This allows performing input/output operations or other long-running tasks without blocking the main thread.
Example of simple asynchronous code:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # simulate asynchronous delay
print("Bye")
async def main():
await asyncio.gather(say_hello(), say_hello())
asyncio.run(main())
Here, the say_hello function is asynchronous; it pauses for a second without blocking the execution of other tasks. In main, we run two such functions in parallel.
Asynchronous mechanisms are useful for network applications, file operations, databases, and other operations where it is important not to block the program while waiting.