Lesson 10: Mutex — Protecting Shared Data
When multiple threads access shared data without synchronisation, a race condition occurs — a bug that is hard to reproduce and can produce wrong data. The mutex (Mutual Exclusion) is the basic mechanism that solves this problem.
A mutex is like a bathroom key: only whoever holds the key can enter. Everyone else waits outside.
- mutex
- Mutual Exclusion — a synchronisation mechanism allowing only one thread to hold the lock at a time, protecting a critical section.
- race condition
- A condition where the outcome depends on the unpredictable order in which threads perform operations. Causes bugs that are hard to reproduce.
- critical section
- A code section where shared data is accessed; must be protected by a mutex to prevent race conditions.
- lock_guard
- A C++ RAII wrapper that locks in the constructor and unlocks in the destructor, guaranteeing the lock is always released even on exceptions.
- deadlock
- A state where two or more threads each wait for the other to release a mutex, and none can proceed.