Concurrency basics

Race conditions, mutexes vs semaphores, producer-consumer, thread pools. One well-explained race condition beats ten definitions.

About 33 min read3-question knowledge check

The mental model

Concurrency is a shared kitchen with one set of knives. Several cooks work at once, which is great for throughput — but the moment two of them reach for the same knife, or one starts a sauce another finishes without noticing it changed, you get a mess that no single cook could have produced alone. Every concurrency bug is a version of that: two threads touching the same thing, and the outcome depending on the exact split-second interleaving of who got there first.

The trap is that the mess is intermittent. A single cook is deterministic — run the recipe twice, get the same dish. Two cooks are non-deterministic: the same code, the same inputs, and sometimes it works and sometimes it corrupts, because the operating system schedules threads differently each run. This is why concurrency bugs are the ones that pass every test, run fine for months, and then surface at 3am under peak load when the interleaving that triggers them finally happens. You cannot debug them by staring at a single thread's logic, because no single thread is wrong.

The core insight that makes concurrency tractable: the problem is always shared mutable state. Remove any one of those three words and the problem vanishes. If state is not shared (each thread has its own copy), no conflict. If it is not mutable (immutable data, read-only), no conflict. If there is no state (pure functions, message passing), no conflict. Every concurrency tool — locks, atomics, immutability, actors, channels — is a different strategy for taming one of those three words.

Why this exists in interviews. One well-explained race condition beats ten definitions. Interviewers use concurrency to find candidates who understand what the hardware and OS actually do versus those who have memorised "use a mutex". The strong signal is showing the interleaving — the exact sequence of two threads' operations that produces the wrong answer — because that proves you understand the mechanism rather than the incantation.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision