Async/Await
Async Functions: The Equivalent of Goroutines
Python provides the async def
syntax for defining asynchronous functions. These functions must be awaited using the await
keyword to execute properly.
import asyncio
async def async_task():
print("Task started")
await asyncio.sleep(2) # Simulate work
print("Task finished")
async def main():
asyncio.create_task(async_task()) # Runs concurrently
print("Main function continues...")
await asyncio.sleep(3) # Wait for the task to complete
asyncio.run(main())
Await Equivalent - Async Queues for Communication
Python's asyncio.Queue
provides a way for coroutines to communicate safely.
import asyncio
async def worker(queue):
await queue.put("Task completed")
async def main():
queue = asyncio.Queue()
asyncio.create_task(worker(queue))
msg = await queue.get() # Like await, wait to receive a message
print(msg) # Output: Task completed
asyncio.run(main())
Buffered vs Unbuffered Queues
Unbuffered queues (default) block until an item is received, while buffered queues allow adding multiple items without an immediate receiver (up to a limit).
import asyncio
async def main():
queue = asyncio.Queue(maxsize=2) # Buffered queue with capacity 2
await queue.put(1) # Non-blocking put
await queue.put(2) # Non-blocking put
print(await queue.get()) # 1
print(await queue.get()) # 2
asyncio.run(main())