Practice free →
HomeGATE CSEcomputerscienceOperating 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._
Solve this in the app — GATE CSE practice & 24k+ MCQs →
Related questions