π 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.
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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.
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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?
π 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.