Home › GATE CSE › computerscience › Operating Systems › Two threads running the unsynchronised counter i…
Two threads running the unsynchronised counter increment `c++` on a shared variable can produce an incorrect final count. This is because
A`c++` is a single atomic operation in C
B`c++` is three ops (load, add, store) interleaved badly
CC++ compilers always parallelise increments correctly
Dthe OS will detect the race automatically
Answer & Solution
Correct answer: B. `c++` is three ops (load, add, store) interleaved badly
1. OSTEP §26.2 (and Ch 28 background) explains why `c++` is unsafe under concurrency.
2. AT THE MACHINE LEVEL, `c++` compiles to three operations:
- LOAD c into register
- ADD 1 to register
- STORE register back to c
3. Race: thread 1 LOADs c=5, gets preempted; thread 2 LOADs c=5, increments to 6, STOREs c=6. Thread 1 resumes, ADDs to 6, STOREs c=6. Final c=6, but TWO increments happened — one was LOST.
4. Mitigation: protect the increment with a lock (mutex), use an atomic increment instruction, or use `std::atomic<int>` in C++.
5. Option A is false (the multi-step nature is exactly the problem). Options C, D are not how concurrency works.
_Source: OSTEP Ch 26 (Concurrency: An Introduction) + Ch 28 (Locks), p. 1-2 + Ch 28 motivation._
Related questions
On a MULTI-CORE system, a SPIN LOCK is generallyDisabling INTERRUPTS as a way to implement mutual exclusion on a single-CPU system isA LIVELOCK differs from a DEADLOCK in thatSuppose thread A acquires lock L1, then thread B acquires lock L2. Now A tries to acquire Without atomic hardware support, building a correct mutual-exclusion lock for $N \geq 2$ tA CRITICAL SECTION isLinux's `pthread_mutex_lock()` is typically implemented as a HYBRID:What is the PRIMARY problem with using a SPIN LOCK on a SINGLE-CPU uniprocessor system (wi