Appearance
12. Multithreading
Concurrency vs Parallelism: concurrency is structure — dealing with multiple things by interleaving (possible on one core); parallelism is execution — actually doing multiple things simultaneously (needs multiple cores).
Why use it: responsiveness (UI thread stays free while a worker computes), resource sharing (no IPC needed — direct shared heap), speed on multicore, better utilization.
CPU-bound vs I/O-bound: CPU-bound (video encoding, ML training) wants threads ≈ number of cores. I/O-bound (web servers, DB queries) wants threads ≫ number of cores.
The shared-memory problem: counter++ isn't atomic — it's LOAD, ADD, STORE. Two threads can both read 0, both increment to 1, both write 1 — one increment is lost.
Classic synchronization problems:
- Producer–Consumer: never push to a full buffer or pop from an empty one; solved with semaphores/condition variables.
- Reader–Writer: many readers may read concurrently, a writer needs exclusive access; writers can starve if readers keep arriving.
- Dining Philosophers: 5 philosophers, 5 forks, need 2 to eat — naive strategy deadlocks; fix by breaking symmetry (one philosopher picks up the opposite fork first) or using a semaphore/monitor.