|
| 1 | +# Asynchronous Programming |
| 2 | + |
| 3 | +*Synchronous Programming*:Synchronous programming, executes the tasks in a predetermined order, where each operation waits for the previous one to complete before proceeding. |
| 4 | + |
| 5 | +*Asynchronous Programming*:Asynchronous programming allows tasks to execute independently of one another, enabling concurrent execution and improved performance. |
| 6 | + |
| 7 | +### `asyncio` in Python |
| 8 | + |
| 9 | +Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, database connection libraries, distributed task queues, etc |
| 10 | + |
| 11 | +1. **Coroutine**: A function defined with `async def` that can be paused and resumed. It runs until it awaits on another coroutine or an `awaitable` object (such as another coroutine, a task, or a future). |
| 12 | +2. **Event Loop**: The core of every asyncio application. It runs asynchronous tasks and callbacks, performs network IO operations, and runs sub-processes. |
| 13 | +3. **Task**: A coroutine wrapped in a task and scheduled to run on the event loop. |
| 14 | +4. **Awaitable**: An object that can be used with await expression, which includes coroutines, Tasks, and Futures. |
| 15 | +5. **Future**: A low-level `awaitable` object that represents a result that will be available in the future. |
| 16 | + |
| 17 | +- Creating and Running coroutines |
| 18 | +```python |
| 19 | +import asyncio |
| 20 | + |
| 21 | +async def greet(name): |
| 22 | + print(f"Hello, {name}") |
| 23 | + await asyncio.sleep(1) |
| 24 | + print(f"Goodbye, {name}") |
| 25 | +async def main(): |
| 26 | + await greet("Alice") |
| 27 | + await greet("Bob") |
| 28 | + |
| 29 | +asyncio.run(main()) |
| 30 | +``` |
| 31 | + |
| 32 | +You can create coroutines using `async def` and run them using `await` |
| 33 | + |
| 34 | +- Running multiple coroutines |
| 35 | + |
| 36 | +```python |
| 37 | +import asyncio |
| 38 | + |
| 39 | +async def greet(name): |
| 40 | + print(f"Hello, {name}") |
| 41 | + await asyncio.sleep(1) |
| 42 | + print(f"Goodbye, {name}") |
| 43 | + |
| 44 | +async def main(): |
| 45 | + await asyncio.gather( |
| 46 | + greet("Alice"), |
| 47 | + greet("Bob") |
| 48 | + ) |
| 49 | + |
| 50 | +asyncio.run(main()) |
| 51 | +``` |
| 52 | + |
| 53 | +You can run multiple coroutines concurrently using `asyncio.gather` or `asyncio.create_task`. |
| 54 | + |
| 55 | + |
0 commit comments