STACK
Ch 04 · Concurrency & Parallelism
Chapter 04 · Many things at once

Concurrency & Parallelism — primitives, models, and traps

Concurrency is dealing with many things at once. Parallelism is doing many things at once. Different problems; different tools. This chapter is the toolkit.

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

ModelHow tasks map to OS threadsExample
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 coroutinesCompile to state machines; no per-task stack.Rust async, C# async, Python async.
Process-basedMultiple OS processes; no shared memory by default.nginx workers, Python multiprocessing.

4.3 · Synchronisation primitives

PrimitiveWhat it doesGotcha
MutexMutual exclusion lock.Deadlock if locked in different orders.
RWLockMany readers OR one writer.Writer starvation under reader load.
SemaphoreN-count permit; bounded resource.Easy to leak permits.
Condition variableWait for predicate; signal others.Spurious wake-ups — always loop on predicate.
BarrierAll N threads must reach point before any proceed.One slow thread blocks everyone.
Latch / CountDownLatchWait until counter hits 0.Single-use.
Atomic opsCAS, fetch-add, etc. Lock-free building blocks.ABA problem.
ChannelTyped queue between goroutines/tasks.Unbuffered = synchronous rendezvous.
Future / PromisePlaceholder for a not-yet result.Don't block in async code.

4.4 · Async / event-loop model

Event loop timers I/O ready (epoll/kqueue) microtask / promise queue callbacks fire
  • 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

HazardDefinitionFix
Race conditionOutcome depends on timing.Lock, atomic, immutable data, single owner.
DeadlockCyclic lock dependency; no progress.Lock ordering; try-lock with timeout.
LivelockThreads keep changing state in response to each other; no work done.Backoff / randomisation.
StarvationA thread never gets the resource.Fair scheduling; bounded priorities.
Priority inversionLow-prio holds lock that high-prio needs.Priority inheritance.
False sharingTwo threads write distinct vars on the same cache line.Pad to cache-line size.
Thundering herdMany 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

LanguageConcurrency idiom
GoGoroutines + channels; sync.Mutex when needed.
Rustasync/await + Tokio; std::sync + channels.
JavaVirtual threads (Loom, JDK 21+), java.util.concurrent.
KotlinCoroutines + Flow; structured concurrency.
C# / .NETasync/await + TPL + channels.
Node / BunEvent loop + Promises + worker_threads for CPU.
Pythonasyncio + trio + anyio; multiprocessing for CPU (GIL).
Elixir / ErlangBEAM processes + OTP supervisors.
SwiftStructured 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