Operating Systems9h estimated

Concurrency & Synchronization

Difficulty
Importance

The problem

When multiple threads read and write the same memory at the same time, the outcome depends on the precise, unpredictable interleaving of their instructions — without a way to coordinate access, the same program can silently produce different results on different runs.

Why now

Processes and threads established that threads share memory; mutability-and-references already showed that shared, mutable data is where aliasing bugs live — synchronization is that same problem, now happening simultaneously across multiple independent lines of execution instead of sequentially in one.

Mental model

A race condition happens when the correctness of a result depends on timing that isn't guaranteed. A lock (mutex) fixes this by making a section of code exclusive — only one thread can be inside at a time, everyone else waits — trading a bit of parallelism for a guarantee that shared state is never read or written mid-update by two threads at once.

Requires

Unlocks

Related

Used in

Projects

  • Reproduce a race condition with two threads incrementing a shared counter without a lock, then fix it with a mutex and verify the result is now always correct
  • Explain, step by step, an interleaving of two threads that produces an incorrect result on an unsynchronized shared counter

Examples

  • Two threads both reading counter=5, both computing 6, both writing 6 — one increment is silently lost
  • A mutex around a bank account balance update ensures a withdrawal and a deposit can never interleave mid-update

Resources

Mastery checklist