πŸŽ“ BookMCQ
← Back to 5. Process Synchronization

πŸ“ Synchronization hardware in operating system (36 MCQs)

Atomic Processor Instructions for Shared-Resource Protection

Synchronization hardware provides atomic processor operations that support safe coordination between concurrently executing processes and threads. These mechanisms belong to the operating system's low-level synchronization facilities and include test-and-set, compare-and-swap, exchange, and atomic increment instructions. Their indivisible execution allows software to build mutexes, spinlocks, and other synchronization primitives without relying solely on ordinary memory reads and writes.

Why Ordinary Read and Write Operations Are Insufficient

Two processors may read the same shared lock before either writes its updated value, allowing both to believe they have acquired exclusive access. Ordinary instructions therefore cannot safely implement lock acquisition through separate checks and updates. Atomic hardware operations combine these actions into indivisible operations, preventing competing processors from successfully performing conflicting acquisitions.

Test-and-Set and Compare-and-Swap Operation

A test-and-set instruction atomically reads a memory location and sets it to a specified value, allowing software to detect whether a lock was previously available. Compare-and-swap checks whether a location contains an expected value and replaces it conditionally. Operating system synchronization routines use these primitives with appropriate memory-ordering rules to implement locks and atomic updates.

Acquiring a Lock with Compare-and-Swap

Suppose a shared lock initially contains zero, meaning unlocked. Two threads attempt compare-and-swap, expecting zero and replacing it with one. Only the first successful operation changes the value and acquires the lock. The second observes that the expected value no longer matches and must retry or wait until the lock becomes available.

Lock Performance, Busy Waiting, and Processor Limitations

Atomic instructions provide efficient building blocks for short critical sections and kernel synchronization. Spinlocks avoid sleeping overhead when lock holding times are small. However, repeated retries consume CPU cycles, and heavily contended atomic variables can cause cache-coherence traffic. Disabling interrupts may protect certain uniprocessor kernel sections but does not provide general mutual exclusion across multiple processors.

Misconceptions About Atomic Synchronization Instructions

'A normal assignment is always atomic' is incorrect because compound memory operations may be interrupted. 'Disabling interrupts protects shared data across all CPUs' is incorrect because it affects only the executing processor's interrupt handling. 'Atomic instructions eliminate deadlocks' is incorrect because higher-level lock ordering can still create circular waits.

Exam Focus: Comparing Atomic Hardware Primitives

Explain test-and-set, compare-and-swap, and exchange using their expected memory effects. Trace two competing lock-acquisition attempts and determine which succeeds. Questions may examine spinlock implementation, atomicity, memory ordering, busy waiting, and why disabling interrupts alone is insufficient for multiprocessor synchronization.

Key Terms of Synchronization Hardware

  • Test-and-set - Atomically reads and updates a lock.
  • Compare-and-swap - Conditional atomic memory replacement.
  • Exchange - Atomically swaps stored values.
  • Spinlock - Lock acquired through repeated checking.
  • Atomicity - Indivisible operation execution.
  • Memory barrier - Enforces memory operation ordering.
12
Easy
12
Medium
12
Hard

πŸ“ All Synchronization hardware in operating system MCQs

Q1. A shared lock is initially 0. Two CPUs execute one truly atomic test-and-set operation at nearly the same time; the operation returns the old value and writes 1. Which result is possible?

A.Both CPUs receive 0 and enter together
B.Neither CPU can modify the lock during contention
C.Both CPUs receive 1 because the lock was initially free
D.One CPU receives 0 and the other receives 1 βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: The atomic operation serializes competing read-modify-write actions at the shared location. The first observes 0 and changes it to 1; the next observes 1, so only one acquisition succeeds at a time.

Q2. A developer implements a lock as separate steps: read lock, check for 0, then write 1. Which execution demonstrates why this is unsafe?

A.Both CPUs execute the read and write as one indivisible action
B.CPU A writes 1 before either CPU reads the lock
C.CPU B reads 1 after CPU A releases the lock
D.CPU A reads 0, CPU B reads 0, then both write 1 and enter βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: The flaw is the gap between checking and updating. Both CPUs can read the same free value before either store occurs, so both believe they acquired the lock and mutual exclusion is violated.

Q3. A thread has a local variable containing 1, while a shared lock contains 0. It atomically exchanges the two values. What does the thread observe afterward?

A.The local variable is 1 and the lock remains 0
B.The exchange fails because the values differ
C.Both variables become 1
D.The local variable becomes 0 and the lock becomes 1 βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: Exchange swaps the two values as one indivisible operation. The thread receives the lock’s previous value 0 in its local variable, while the shared lock receives 1, indicating successful acquisition.

Q4. A shared state contains 7. A compare-and-swap operation expects 7 and requests replacement with 9. Under the usual return-old-value definition, what happens?

A.It returns failure and changes the state to 0
B.It returns 9 and leaves the state at 7
C.It returns 7 and leaves the state unchanged
D.It returns 7 and changes the state to 9 βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: The observed value matches the expected value, so compare-and-swap performs the replacement atomically. With return-old-value semantics it returns 7, and the shared state becomes 9 on the same shared memory location.

Q5. A ticket counter starts at 41. Two threads each perform one atomic fetch-and-add by 1. Which pair of returned ticket values and final counter is possible?

A.Both receive 41; final counter is 42
B.They receive 41 and 43; final counter is 44
C.They receive 42 and 42; final counter is 43
D.They receive 41 and 42; final counter is 43 βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: Each fetch-and-add returns the old counter and increments it indivisibly. The operations therefore receive distinct consecutive values, 41 and 42, and leave the shared counter at 43 without a lost update from a competing caller.

Q6. A payroll service protects a shared request counter. Why can an ordinary read followed by an ordinary write lose increments when two worker threads run concurrently?

A.A read operation always resets the counter to zero
B.Both workers may read the same old value and overwrite one another’s increment βœ…
C.The scheduler prevents arithmetic instructions from completing
D.A normal integer cannot store values written by two threads
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– Explanation: An increment is a read-modify-write sequence, not necessarily one indivisible action. If both workers read the same old value, each can store the same incremented result, losing one update during the same interleaving.

Q7. A team proves that its test-and-set lock permits only one owner at a time. What additional property is not established merely by that mutual-exclusion guarantee?

A.That the lock variable can be represented in memory
B.That the atomic instruction changes its target
C.That two owners cannot enter simultaneously
D.That every waiting thread eventually acquires the lock βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: Mutual exclusion limits simultaneous ownership, but test-and-set does not prescribe a fair queue. A thread may repeatedly lose races to reacquiring competitors, so bounded waiting or starvation freedom is not automatic.

Q8. A uniprocessor kernel disables local interrupts while updating a short shared structure. Why is this not a general lock for a multicore machine?

A.It prevents the other CPUs from executing every instruction
B.It only suppresses interrupt-driven preemption on the CPU that performs the operation βœ…
C.It makes ordinary stores atomic across all cache copies
D.It automatically transfers all other CPUs into kernel mode
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– Explanation: Disabling interrupts affects the executing processor’s interrupt handling. Other CPUs can continue running and access the same shared memory, so a multiprocessor system still needs coordination visible to all participants.

Q9. A spinlock owner is descheduled while three other CPUs repeatedly attempt test-and-set. What is the immediate cost to the waiting CPUs?

A.The scheduler converts the spinlock into a blocking mutex
B.They enter the protected region because the owner is not running
C.Their failed instructions release the lock automatically
D.They consume processor cycles retrying while the owner cannot release the lock βœ…
πŸ’‘ Difficulty: easy | βœ… Correct: D

πŸ“– Explanation: A preempted owner still holds the lock. Waiting CPUs continue executing retry loops rather than useful application work, and the lock cannot become available until its owner runs and releases it.

Q10. A database team argues that atomic exchange eliminates deadlock because every exchange instruction completes. Which response is correct?

A.Correct, because deadlock requires an unfinished machine instruction
B.Correct, because atomic operations release all other locks
C.Incorrect, because completed atomic instructions can still be used in a circular-wait protocol βœ…
D.Incorrect, because exchange is not atomic on shared memory
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: Atomicity describes an individual operation, not the global resource-allocation protocol. Threads can complete their exchange instructions and still wait indefinitely for locks held by one another even when every primitive itself completes correctly.

Q11. A programmer uses atomic fetch-and-add to count accepted orders, then separately checks stock and reserves an item. Which statement is safest?

A.The atomic increment makes the later stock check and reservation indivisible
B.The counter can never be read by another thread
C.The entire stock invariant still needs a coordinated atomic protocol or lock βœ…
D.The stock check should always be performed before every increment without synchronization
πŸ’‘ Difficulty: easy | βœ… Correct: C

πŸ“– Explanation: Fetch-and-add makes only its own counter update indivisible. The stock check and reservation form a larger compound action, so another worker may intervene unless that invariant is protected as a unit.

Q12. A process receives the old value 1 from test-and-set on a Boolean lock where 1 means held. What should its spinlock code do?

A.Enter immediately because the instruction completed
B.Treat this attempt as unsuccessful and retry or wait βœ…
C.Write 0 before entering, regardless of the owner
D.Assume the other process has terminated
πŸ’‘ Difficulty: easy | βœ… Correct: B

πŸ“– Explanation: Test-and-set returns the value that existed before it set the target. An old value of 1 means the lock was already held, so this caller did not acquire ownership and must remain outside.

Q13. Lock L is 0. Thread A executes compare-and-swap expecting 0 and replacing it with 1. Before A releases L, thread B executes the same operation. Using return-old-value semantics, what are the two results in order?

A.Both return 1 and leave L at 1
B.A returns 1; B returns 0 and leaves L at 0
C.Both return 0 and leave L at 1
D.A returns 0; B returns 1 and leaves L at 1 βœ…
πŸ’‘ Difficulty: medium | βœ… Correct: D

πŸ“– Explanation: A’s comparison succeeds first, returning 0 and storing 1. B then compares against 0 while L is 1, so it returns 1 without changing the lock; only A owns it.

Q14. A thread uses test-and-set on a lock initialized to false. The operation returns false and sets the lock to true. Which condition must hold before the thread enters the critical section?

A.It must observe that the returned old value was false βœ…
B.It must wait until the lock becomes false again
C.It must set the lock to false before entering
D.It must receive true from a second test-and-set
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: The returned value records the lock state before the atomic update. False indicates that this thread changed the previously free lock to held; a true return indicates another owner already held it.

Q15. A resource counter is 1. Two workers each try to reserve one unit using compare-and-swap from 1 to 0. What is the valid outcome?

A.Both succeed because each expected the initial value 1
B.Exactly one succeeds; the other sees a mismatch and must not claim the unit βœ…
C.Neither succeeds because compare-and-swap cannot write zero
D.The counter becomes negative one
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: The first successful operation changes the counter from 1 to 0 atomically. The second operation no longer sees its expected value, so it fails and cannot allocate the same final unit.

Q16. A lock uses atomic exchange. Shared lock L is 1 and a contender’s local key is 1. After one exchange, what values result, and has the contender acquired the lock?

A.L is 1 and key is 1; yes, it owns the lock
B.L is 0 and key is 0; yes, it owns the lock
C.L is 1 and key is 1; no, it has not acquired the lock βœ…
D.L is 0 and key is 1; no, the exchange did not occur
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– Explanation: Exchange swaps equal values in this case, leaving both at 1. The returned old lock value is 1, which signals that the lock was already held; the contender must retry.

Q17. Two threads each perform 500 increments. A faulty interleaving loses 37 increments because their load-add-store sequences overlap. What final value should the shared counter contain if it began at 100?

A.1063 βœ…
B.1100
C.563
D.963
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: There are 1000 intended increments, but 37 updates are lost. The final value is therefore 100 + 1000 - 37 = 1063; an atomic increment would prevent these lost counter updates.

Q18. A ticket lock assigns values using atomic fetch-and-add. The next-ticket counter is 12 and two threads request tickets. What does the primitive guarantee, independent of which CPU runs first?

A.The thread with the lower process ID receives 12
B.Both threads receive the same ticket if they run concurrently
C.The requests obtain distinct values 12 and 13 in one serialized order βœ…
D.The thread receiving 13 must enter before the thread receiving 12
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– Explanation: Atomic fetch-and-add serializes modifications to the shared counter. The two callers receive distinct old values, 12 and 13, although scheduling determines which caller receives each value as each caller reaches the shared counter.

Q19. A CAS-based state update expects READY and writes RUNNING. The actual state is FAILED. What should the operation do?

A.Replace FAILED with RUNNING because the new state has priority
B.Leave FAILED unchanged and report that the expected-state comparison failed βœ…
C.Change FAILED to READY before retrying automatically
D.Return success without modifying the state
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: Compare-and-swap changes the location only when its current value equals the expected value. Since FAILED does not match READY, the transition must fail and leave the shared state unchanged and the caller must handle that failed transition.

Q20. A producer writes payload = 42 and then publishes ready = 1. A consumer observes ready = 1 but may still read an old payload on a weakly ordered system. Which addition addresses the ordering requirement?

A.A release operation before publishing ready and an acquire operation after observing it βœ…
B.A longer delay after the consumer reads payload
C.A larger integer type for ready
D.An ordinary assignment replacing both writes
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: A release barrier orders the payload write before publication, while an acquire barrier orders the consumer’s later payload read after observing readiness. These ordering guarantees do not make unrelated ordinary data atomic.

Q21. A lock’s compare-and-swap succeeds, but protected data is occasionally observed stale by another CPU after lock handoff. Which diagnosis best fits?

A.The compare operation must have returned a random value
B.The protected data is necessarily stored on disk
C.The lock operation may lack acquire-release memory ordering around critical-section accesses βœ…
D.Every successful CAS automatically clears all processor caches
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– Explanation: Atomicity protects the lock state transition, but visibility of other memory accesses also depends on ordering semantics. Acquire on lock success and release on unlock provide the required synchronization ordering.

Q22. A student replaces an atomic lock acquisition with: read L; if L = 0, write L = 1. The student claims the sequence is safe because each individual read and write is valid. What is the precise error?

A.The lock must be represented using a floating-point type
B.The separate operations permit another thread to pass the check before the first store βœ…
C.The write must set L to 0 instead
D.A lock cannot be read by more than one CPU
πŸ’‘ Difficulty: medium | βœ… Correct: B

πŸ“– Explanation: The flawed step is treating individually valid instructions as one atomic action. The correct approach is to combine the comparison and update in a hardware atomic primitive so competing threads cannot both claim the same free lock.

Q23. A developer uses compare-and-swap with return-old-value semantics, but writes `if (CAS(L, 0, 1)) enter`. L is initially 0. What is wrong?

A.The test treats the returned old value 0 as failure, so the successful acquisition is rejected βœ…
B.CAS cannot replace a zero value with one
C.The condition is correct because zero always means success in Boolean contexts
D.The lock must start at one for the code to work
πŸ’‘ Difficulty: medium | βœ… Correct: A

πŸ“– Explanation: With return-old-value semantics, a successful CAS returns the previous value 0. The condition therefore evaluates as false; the code should test equality with zero rather than use the value directly as a success flag.

Q24. A reviewer sees a test-and-set result of true and says the caller has acquired the lock because the instruction set the target to true. What is the correction?

A.The reviewer is correct because the new value determines ownership
B.The caller owns the lock only if the returned old value was true
C.The returned old value was true, so the lock was already held and this attempt failed βœ…
D.The instruction must be repeated with an ordinary store before entry
πŸ’‘ Difficulty: medium | βœ… Correct: C

πŸ“– Explanation: The flawed reasoning confuses the new lock value with the returned previous value. Test-and-set writes true in either case, but only an old false value indicates that this caller changed a free lock to held.

Q25. An engineer disables interrupts on CPU 0 while updating shared data and assumes CPU 1 cannot interfere. Identify the flawed assumption and the correct protection.

A.Interrupt disabling on CPU 0 disables interrupts and execution on every CPU
B.CPU 1 may continue executing; use a shared atomic lock or another multiprocessor-safe protocol βœ…
C.CPU 1 cannot access shared memory while CPU 0 is in kernel mode
D.Interrupt disabling automatically creates a global memory barrier and lock
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: The mistaken step is assuming local interrupt masking stops another processor. CPU 1 can still access shared memory; protection must use an atomic operation or synchronization mechanism honored by every participating CPU.

Q26. A programmer replaces a lock around `check balance; subtract amount; update ledger` with one atomic increment on a transaction counter. Why is the replacement incorrect?

A.Atomic increment only makes its own counter update indivisible; the balance and ledger invariant remains unprotected βœ…
B.An atomic increment always takes longer than a mutex
C.A transaction counter cannot be shared by threads
D.The increment automatically rolls back if the balance is insufficient
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: The flawed step is assuming one atomic update protects separate shared objects. The check, subtraction, and ledger update must remain coordinated as one invariant-preserving operation through a suitable lock or atomic protocol.

Q27. A benchmark records failed spinlock attempts per millisecond as CPU contenders increase. Data points are (1, 2), (2, 6), (4, 19), (8, 61), and (16, 174). Which trend is supported?

A.Failed attempts decrease as more CPUs compete
B.Failed attempts rise sharply with contention, increasing retry and coherence costs βœ…
C.The measurements prove that mutual exclusion has failed
D.The retry count remains constant after two CPUs
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: The recorded values rise from 2 to 174 as contenders increase from 1 to 16. This indicates heavier retry activity under contention; it does not by itself show that the lock permits multiple owners.

Q28. A graph gives average lock acquisition latency in microseconds: (1, 1), (2, 2), (4, 4), (8, 10), (16, 27), (32, 68). At 16 contenders, what latency should be read?

A.4 microseconds
B.10 microseconds
C.27 microseconds βœ…
D.68 microseconds
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: The point with x = 16 contenders is (16, 27). Therefore the plotted average acquisition latency is 27 microseconds; the other values belong to different contender counts in the plotted data.

Q29. A web server records waiting worker threads while the lock owner is descheduled and new requests arrive. The data are (time 0, 1), (time 1, 3), (time 2, 5), (time 3, 7), (time 4, 9). Which interpretation best matches this pattern?

A.The number of waiters rises by two per time unit while the owner cannot run and release the lock βœ…
B.The lock has been released at every time point
C.Each waiting thread has entered the critical section
D.The graph establishes that the atomic instruction is not indivisible
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: The waiter count increases from 1 to 9 in equal increments as new requests arrive while the owner is unavailable. More workers must wait or spin; this pattern reflects contention, not a mutual-exclusion failure.

Q30. A system measures completed protected operations per second as lock shards increase: (1, 100), (2, 180), (4, 285), (8, 315), (16, 320), (32, 321). Where does the graph first show strong diminishing returns?

A.From 1 to 2 shards
B.From 2 to 4 shards
C.From 4 to 8 shards
D.Beyond 8 shards, where gains become small βœ…
πŸ’‘ Difficulty: hard | βœ… Correct: D

πŸ“– Explanation: Throughput rises substantially up to eight shards, from 100 to 315 operations per second. It then increases only to 320 and 321, showing that additional sharding yields minimal improvement as additional shards are added.

Q31. A web server protects a task that routinely holds a lock for 20 milliseconds, and competing workers often sleep while waiting. Which design is generally more suitable than a tight spin loop?

A.A blocking mutex, or redesign that shortens the protected interval βœ…
B.An aggressive test-and-set loop with no pause
C.Disabling interrupts on every CPU for the entire task
D.An ordinary check-then-set sequence
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: Spinning is useful when waits are very short and owners are expected to run. For millisecond holds with frequent contention, blocking avoids burning CPU cycles while a waiter cannot proceed.

Q32. A shared queue is protected by one atomic lock. Two independent queues are then given separate locks, but a transfer operation must modify both queues. What additional rule is important?

A.The transfer should ignore one lock because each queue has its own lock
B.All operations must use a consistent lock order when acquiring both locks βœ…
C.The separate locks make the transfer automatically atomic
D.The system should replace both locks with ordinary flags
πŸ’‘ Difficulty: hard | βœ… Correct: B

πŸ“– Explanation: Separate locks reduce contention for independent operations, but a transfer spans both protected structures. Acquiring the two locks in a consistent global order helps prevent circular wait while preserving the combined invariant.

Q33. A lock-free stack uses CAS on its head pointer. A thread reads address A, pauses, and later sees address A again after another thread removed and reinserted a node at that address. What is the key risk?

A.The ABA problem: the pointer value matches although intervening changes occurred βœ…
B.The CAS operation has become a non-atomic ordinary store
C.The node address can no longer be represented by the processor
D.A matching pointer proves that the stack history is unchanged
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: The head changes from A to another value and later returns to A, so a simple comparison misses the intervening history. Tagged versions or safe memory-reclamation techniques can address this risk.

Q34. A lock-free counter uses a CAS retry loop. One thread repeatedly wins while another repeatedly fails, although the counter continues changing. Which statement best distinguishes system progress from individual fairness?

A.The algorithm guarantees every thread the same number of successful updates
B.The losing thread must already own the counter
C.The system may make progress while an individual thread experiences starvation βœ…
D.Repeated CAS failure means the hardware atomicity guarantee has failed
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: Successful updates by some threads show system-wide progress, but they do not guarantee that each contender succeeds. CAS retry loops can therefore be lock-free while an individual thread experiences prolonged failure or starvation.

Q35. Two CPUs use CAS to change a shared resource count from 2 to 1. One succeeds; the other fails and rereads the count. It then retries using the newly observed value. What is the essential reason for retrying from a fresh observation?

A.The old expected value may no longer match the shared state after another successful update βœ…
B.CAS requires every thread to use the same expected value forever
C.The failed operation must have reset the resource count to zero
D.A retry makes the earlier successful update disappear
πŸ’‘ Difficulty: hard | βœ… Correct: A

πŸ“– Explanation: A failed CAS means the comparison did not match at its atomic execution point. The thread must use a current observation and recompute its desired state; reusing stale assumptions can overwrite or miscount concurrent updates.

Q36. A multicore operating system uses atomic exchange for lock acquisition, but a critical section may acquire locks X and Y in different orders on different paths. What conclusion follows?

A.Atomic exchange prevents circular wait regardless of lock order
B.Each exchange completes, so the two paths cannot deadlock
C.The hardware primitive is still valid, but inconsistent lock ordering can create deadlock βœ…
D.The system should disable interrupts only on the first CPU
πŸ’‘ Difficulty: hard | βœ… Correct: C

πŸ“– Explanation: The atomic exchange can correctly protect each individual lock while the larger protocol remains unsafe. If threads acquire X and Y in opposite orders, each may hold one and wait forever for the other.

πŸ”— Related Topics (MCQs)