4.1 · Concurrency vs parallelism
The Rob Pike line
Concurrency is composition of independently executing things. Parallelism
is simultaneous execution of (possibly related) computations. You can have either without the other.
4.2 · Execution models
| Model | How tasks map to OS threads | Example |
|---|---|---|
| 1:1 (OS threads) | One user thread per kernel thread. | pthreads, Java < 21. |
| N:1 (cooperative) | Many tasks on one OS thread, scheduled by language runtime. | Node event loop. |
| M:N (multiplexed) | Many tasks on N OS threads; runtime scheduler. | Goroutines, Java virtual threads, Erlang processes, Tokio. |
| Stackless coroutines | Compile to state machines; no per-task stack. | Rust async, C# async, Python async. |
| Process-based | Multiple OS processes; no shared memory by default. | nginx workers, Python multiprocessing. |
4.3 · Synchronisation primitives
| Primitive | What it does | Gotcha |
|---|---|---|
| Mutex | Mutual exclusion lock. | Deadlock if locked in different orders. |
| RWLock | Many readers OR one writer. | Writer starvation under reader load. |
| Semaphore | N-count permit; bounded resource. | Easy to leak permits. |
| Condition variable | Wait for predicate; signal others. | Spurious wake-ups — always loop on predicate. |
| Barrier | All N threads must reach point before any proceed. | One slow thread blocks everyone. |
| Latch / CountDownLatch | Wait until counter hits 0. | Single-use. |
| Atomic ops | CAS, fetch-add, etc. Lock-free building blocks. | ABA problem. |
| Channel | Typed queue between goroutines/tasks. | Unbuffered = synchronous rendezvous. |
| Future / Promise | Placeholder for a not-yet result. | Don't block in async code. |
4.4 · Async / event-loop model
- Single-threaded; never block — that stalls everything.
- CPU-bound work → worker threads or processes.
- "Callback hell" → Promises → async/await.
- Order: microtasks (Promise then) drain after each task; macrotasks (I/O, timers) one per loop iteration.
4.5 · Actors & channels
- Actor: isolated state + mailbox + behaviour. Communicates only via messages.
- Erlang / Elixir: millions of actors; supervisor trees restart on failure ("let it crash").
- Akka (JVM), CAF (C++), Orleans (.NET) ports the model.
- CSP / channels: Go and Rust prefer channels over actors. Don't share memory by communicating; communicate by sharing memory (Pike).
4.6 · Lock-free & atomics
- CAS (compare-and-swap): atomic
if (mem == expected) mem = new. Foundation of lock-free. - LL/SC (load-linked / store-conditional): ARM equivalent.
- Lock-free queues: Michael-Scott queue is the classic.
- ABA problem: value flips A→B→A between read and CAS; mitigations: tagged pointers, hazard pointers, epoch-based reclamation.
- Lock-free ≠ fast. Often slower than well-tuned locks under contention; pick by measurement.
4.7 · Concurrency hazards
| Hazard | Definition | Fix |
|---|---|---|
| Race condition | Outcome depends on timing. | Lock, atomic, immutable data, single owner. |
| Deadlock | Cyclic lock dependency; no progress. | Lock ordering; try-lock with timeout. |
| Livelock | Threads keep changing state in response to each other; no work done. | Backoff / randomisation. |
| Starvation | A thread never gets the resource. | Fair scheduling; bounded priorities. |
| Priority inversion | Low-prio holds lock that high-prio needs. | Priority inheritance. |
| False sharing | Two threads write distinct vars on the same cache line. | Pad to cache-line size. |
| Thundering herd | Many threads wake on one event; all but one fail. | Conditional wake / SO_REUSEPORT. |
4.8 · Concurrency patterns to recognise
- Producer/Consumer via bounded channel.
- Worker pool — fan-out N workers reading one queue.
- Pipeline — stages connected by channels.
- Fan-out / fan-in — broadcast and collect.
- Map-reduce in-process — concurrent transform + aggregate.
- Read-copy-update (RCU) — write to copy, atomically swap pointer.
- Per-thread / per-core sharding — avoid contention by partitioning.
- Bulkhead — separate thread pools per dependency.
- Backpressure — bounded queues + signal to producer.
4.9 · Per-language flavour
| Language | Concurrency idiom |
|---|---|
| Go | Goroutines + channels; sync.Mutex when needed. |
| Rust | async/await + Tokio; std::sync + channels. |
| Java | Virtual threads (Loom, JDK 21+), java.util.concurrent. |
| Kotlin | Coroutines + Flow; structured concurrency. |
| C# / .NET | async/await + TPL + channels. |
| Node / Bun | Event loop + Promises + worker_threads for CPU. |
| Python | asyncio + trio + anyio; multiprocessing for CPU (GIL). |
| Elixir / Erlang | BEAM processes + OTP supervisors. |
| Swift | Structured concurrency, actors (since 5.5). |
4.10 · Self-check
Q1 · "Don't share memory by communicating; communicate by sharing memory." Which language popularised this?
Rust
Java
Go
Erlang