3.1 Threading vs Multiprocessing
Python offers two main ways to achieve parallelism:
- Threading: Good for I/O-bound tasks. Limited by the Global Interpreter Lock (GIL).
- Multiprocessing: Good for CPU-bound tasks. Bypasses the GIL by creating separate processes.
3.2 The `asyncio` Library
asyncio is a library to write concurrent code using the async/await syntax. It is used as a foundation for multiple Python asynchronous frameworks (like FastAPI).
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
3.3 Event Loops and Coroutines
The event loop is the core of every asyncio application. It runs asynchronous tasks and callbacks, performs network IO operations, and runs subprocesses.
🎯 Practical Exercise
Write a script that fetches data from 3 different URLs concurrently using aiohttp and asyncio.