Interview frequency: …
Short answer
A critical section is code that accesses a mutable shared resource. A race condition occurs when multiple threads compete to access and modify that resource simultaneously without proper synchronization.
Explanation
A classic example is the simple count++ operation. At the machine level it consists of three instructions: (1) read the value from memory into a register; (2) increment it; and (3) write it back to memory. If two threads do this at the same time, they may both read 5, calculate 6, and write 6 instead of 7! This unpredictable data loss is a serious race condition.
Code example
// Unsafe multithreaded code:
int counter = 0;
void increment() {
counter++; // Non-atomic and causes Race Condition
}Common mistakes
- Believing that a single line of code (such as x++) is an atomic, thread-safe operation.