‹ All Operating Systems questions

Operating Systems Practice Question 2: Shared Counter Race

Operating Systems · Test 1 · question 2 of 10

Concurrency & Synchronizationeasy

A program starts two threads. Each thread runs counter = counter + 1 one million times on a shared global counter that starts at 0, with no locking. Run on a multi-core machine, the final value is usually less than 2,000,000, and it changes from run to run.

What is the best description of this problem?

Select one answer
Show answer and explanation

Answer:

  • D. A race condition, because the unprotected increment is a critical section that is not atomic

counter = counter + 1 compiles to several instructions: load the value into a register, add one, store it back. If one thread is interrupted (or runs in parallel on another core) between the load and the store, both threads can load the same old value and both store the same new value; one increment is lost. The code that touches the shared variable is a critical section, and when multiple threads enter it at roughly the same time the result depends on timing: a race condition (data race). The fix is mutual exclusion, a lock around the increment, or an atomic increment instruction.

Option A is wrong: a deadlock means threads stop making progress. Here both threads finish; they just produce the wrong answer. There are no locks at all to wait on.

Option B is wrong: even if one thread ran much more often, every increment would still be counted if increments were atomic. Starvation delays work; it does not lose updates.

Option C is wrong: 2,000,000 fits easily in a 32-bit integer, and overflow would give a consistent wrong value rather than a different one each run.

Reference: OSTEP - Concurrency: An Introduction

Practice Test 1 ›