35. Concurrency & Parallelism
Master concurrent & parallel execution in Python: understand the key differences between Sequential Execution, I/O-Bound Concurrency via threading, CPU-Bound Multi-Core Parallelism via multiprocessing, Event-Driven Cooperative Multitasking with asyncio, Thread Safety, Race Conditions, and Mutex Locks.
🎓 Junior Python Curriculum — Select Module
Threading & Concurrency
Interleaved execution ideal for I/O-bound tasks (HTTP requests, file I/O). Threads share memory space and release the Global Interpreter Lock (GIL) during blocking I/O calls.
- `threading.Thread`: Lightweight threads sharing process memory.
- `ThreadPoolExecutor`: Managed pool for concurrent I/O.
- GIL Impact: Cannot run CPU-bound tasks in parallel.
Multiprocessing Parallelism
True multi-core parallelism for CPU-bound tasks (image processing, mathematical computation). Bypasses GIL by spawning distinct OS processes with dedicated memory spaces.
- `multiprocessing.Process`: Separate OS processes.
- `ProcessPoolExecutor`: Multi-core CPU task distribution.
- Memory Isolation: No shared memory state by default.
Thread Safety & Mutex Locks
Race conditions occur when multiple threads mutate shared data simultaneously. Mutex Locks (`threading.Lock`) enforce mutual exclusion, guaranteeing thread-safe operations.
- Race Condition: Data corruption from unsynchronized writes.
- `threading.Lock()`: Acquire and release lock context.
- `asyncio`: Single-threaded non-blocking cooperative loop.
Threading, Multiprocessing & Lock Synchronization
🧵 Threading & GIL
Interleaved execution ideal for IO-bound work (network, disk). Releases GIL during blocking I/O calls.
⚡ Multiprocessing Parallelism
True multi-core CPU compute bypassing the Global Interpreter Lock (GIL) via distinct OS processes.
🔒 Thread Safety & Asyncio
Prevent race conditions with `threading.Lock()` and coordinate single-threaded event loops with `asyncio`.
=== EXECUTION RESULT === Sequential I/O Time (4 tasks @ 0.1s each): 402.15 ms Threaded I/O Time (4 concurrent threads): 101.45 ms Concurrency Speedup Factor: 3.96x faster!
35. Concurrency & Parallelism Comparison Matrix
📊 Concurrency Models & Paradigm Matrix
| Paradigm | Module | Ideal Workload | GIL Impact | Memory Model |
|---|---|---|---|---|
| Sequential | Built-in | Simple step-by-step logic | Single Thread | Single Process Memory |
| Threading | `threading` | I/O-Bound (Web, Files, Network) | Subject to GIL (Releases on I/O) | Shared Process Memory |
| Multiprocessing | `multiprocessing` | CPU-Bound (Heavy Math, Data) | Bypasses GIL (Multi-Core) | Isolated Process Memory |
| Asyncio | `asyncio` | High-Concurrency I/O APIs | Single Threaded Event Loop | Single Event Loop Context |