π Semaphore Implementation in Process Synchronization (36 MCQs)
Internal Representation of Semaphore Operations
Semaphore implementation concerns how an operating system performs atomic wait and signal operations while maintaining a semaphore value and managing blocked processes. A semaphore typically includes an integer state and a waiting queue. Its implementation must prevent simultaneous modifications from competing execution activities and ensure that permits are correctly allocated when processes acquire or release resources.
Why Atomic Updates and Waiting Queues Are Necessary
If two processes modify a semaphore through ordinary unprotected instructions, they may both consume the same permit or incorrectly update its value. Atomic operations prevent these conflicts. When no permit is available, keeping processes in a waiting queue avoids wasting processor time through continuous polling and supports controlled wake-up operations.
Blocking Wait and Wake-Up Signal Implementation
A blocking semaphore implementation performs an atomic wait operation, reducing its value when a permit exists. If no permit is available, the process is placed in the semaphore's waiting queue and its execution is blocked. A signal operation increases availability and may remove a waiting process from the queue, making it eligible for scheduling.
Two Processes Competing for One Semaphore Permit
Suppose a binary semaphore begins at 1. Process P1 performs wait and obtains the permit, changing the state to unavailable. P2 attempts wait and enters the blocked queue. When P1 performs signal, the implementation wakes P2 or makes the permit available according to its chosen convention, allowing controlled continuation.
Implementation Overhead, Queue Management, and Fairness
Blocking implementations avoid continuous CPU consumption when processes wait for resources and are suitable for longer critical sections. However, queue management, context switching, and scheduler interaction introduce costs. Some implementations use atomic spinning for short waits before blocking. Queue-selection policies also influence fairness, and incorrect implementation can cause lost wake-ups or starvation.
Misconceptions About Semaphore Internal Behaviour
'Every semaphore uses busy waiting' is incorrect because blocking implementations suspend waiting processes. 'The semaphore value alone stores every waiting process' is incorrect because implementations also need waiting-state management. 'Waking a process means it executes immediately' is incorrect because it must still be scheduled by the operating system.
Exam Focus: Tracing Semaphore Values and Waiting Queues
Trace the integer state, atomic wait operation, signal operation, and waiting queue during competing requests. Distinguish blocking implementations from spin-based approaches and explain how wake-up interacts with CPU scheduling. Questions may examine lost wake-ups, queue management, permit allocation, implementation atomicity, and the difference between becoming ready and immediately executing.
Key Terms of Semaphore Implementation
- Wait queue - Stores blocked semaphore participants.
- Blocking - Suspension while awaiting a permit.
- Wake-up - Makes a waiting process eligible.
- Atomic update - Indivisible semaphore state modification.
- Scheduler - Selects eligible execution activities.
- Lost wake-up - Notification missed by a waiter.
π All Semaphore Implementation in Process Synchronization MCQs
Q1. Two kernel threads call wait(S) at nearly the same time when S has one available permit. Which implementation property prevents both threads from obtaining it?
π Explanation: The availability check and decrement must be atomic. Otherwise, both threads could read the same positive value before either update becomes visible, allowing two acquisitions from one permit and violating semaphore correctness.
Q2. S has value 0, and process P calls wait(S) in a blocking implementation. What should happen when no permit is available?
π Explanation: With no available permit, wait must not let P enter the protected region. The implementation records P as waiting and blocks it, allowing the scheduler to run another eligible process.
Q3. A semaphore follows the convention that wait first decrements its integer and blocks a caller if the result is negative. It starts at 2, and four distinct processes each call wait once without any signal. What are the final value and blocked-process count?
π Explanation: The successive values are 1, 0, -1, and -2. Only the third and fourth callers encounter negative results and block, so the final count is -2 and the queue contains two processes.
Q4. One implementation reports S = -3 while three processes wait; another implementation stores a nonnegative count and keeps waiters only in a separate queue. Which statement is correct?
π Explanation: Semaphore implementations use different internal conventions. A negative count may encode the number of waiters, while another design stores availability separately from its queue; consistency across all wait and signal operations determines correctness.
Q5. A semaphore uses a nonnegative free-permit count and a separate wait queue. The count is 0 and two processes are queued. One signal occurs using direct handoff. What should the operation do?
π Explanation: Under direct handoff, the released opportunity is assigned to one selected waiter rather than advertised as a free permit. Therefore one process is awakened and the separate count can remain zero.
Q6. A student writes wait(S) as two unprotected steps: first test whether S is positive, then decrement it. With S = 1, two CPUs run the code concurrently. Which line of reasoning is flawed?
π Explanation: The flawed reasoning assumes adjacency makes separate instructions indivisible. The correct requirement is atomicity across the test and update, so competing CPUs cannot both claim the single available permit concurrently.
Q7. Two CPUs execute signal(S) concurrently when S = 4. The implementation uses an ordinary load followed by an ordinary addition and store, without protection. What incorrect result is possible?
π Explanation: Both CPUs may read 4, independently compute 5, and store 5. One increment is then lost; the correct implementation makes each update atomic or protects the shared count against concurrent modification.
Q8. A trace uses a negative-count convention. Events occur in this order: initial S = 2; P calls wait; Q calls wait; R calls wait; then one signal occurs. Which final state matches the trace?
π Explanation: The waits change S from 2 to 1, 0, and -1; R blocks. The signal raises S to 0 and wakes one queued process, leaving no waiter in this three-process trace.
Q9. A system replaces a polling-based semaphore with one that blocks processes during long resource waits. Which performance effect is the main intended benefit?
π Explanation: Blocking suspends a process that cannot make progress and lets the scheduler choose other work. Queueing and wake-up have costs, but long waits no longer waste CPU through repeated polling.
Q10. A kernel protects a semaphore count and linked wait queue with a spinlock. A thread keeps that spinlock while performing a slow disk read. Why is this implementation harmful?
π Explanation: A spinlock should protect only a very short critical section. Holding it during slow I/O forces competing CPUs to waste cycles spinning and prevents prompt access to the semaphore bookkeeping.
Q11. A signal operation removes a blocked process from a semaphore queue and places it in the ready queue. The process does not run until later. Which process-state interpretation is correct?
π Explanation: Wake-up changes a blocked process into a ready process; it does not assign a processor immediately. The scheduler chooses when that process actually runs, subject to priority and scheduling policy.
Q12. A semaphore uses a FIFO wait queue. P, Q, and R become blocked in that order, and one signal selects a single waiter. Which process is selected?
π Explanation: FIFO service selects the process that entered the queue first. Since P arrived before Q and R, P is removed and awakened by the next signal, assuming no cancellation or queue reset.
Q13. A semaphore wakes waiters in FIFO order, but the CPU scheduler repeatedly gives processor time to newly arriving high-priority tasks. Why might the oldest awakened waiter still wait?
π Explanation: Queue policy determines which blocked process is made ready first. Actual execution depends on CPU scheduling, so FIFO wake-up alone does not guarantee immediate service or a bounded time to run.
Q14. A single-core implementation disables interrupts while changing a semaphore count. The same design is copied unchanged to a four-core machine. What is the main flaw?
π Explanation: Local interrupt masking prevents certain interruptions on the current processor only. Another core may still execute a competing operation, so shared semaphore state needs multiprocessor-safe atomicity or a lock across the whole machine.
Q15. An implementation uses atomic fetch-and-add to increase S during signal. A blocked process remains asleep because no queue or wake-up logic runs. What is missing?
π Explanation: Fetch-and-add makes the integer update indivisible, but it does not manage sleeping processes. A complete blocking implementation must coordinate the count with the wait queue and the operating system wake-up mechanism.
Q16. A wait operation repeatedly retries compare-and-swap while many threads compete. The system as a whole makes progress, but one thread repeatedly loses and never acquires the permit. Which property is not guaranteed?
π Explanation: An atomic retry loop can preserve the shared count while allowing some thread to make progress. Without a fair queue or another guarantee, one unlucky contender may repeatedly lose and starve.
Q17. A blocking semaphore stores an integer and a queue of process identifiers. Why are both components useful in this representation?
π Explanation: The integer records semaphore availability or outstanding demand, depending on the chosen convention. The queue records which processes are suspended, allowing signal to select and wake an eligible waiter in the shared system.
Q18. A signaler increments a shared free-permit count and wakes a waiter. Before the waiter runs, a newly arriving process consumes the incremented permit. Which design prevents the selected waiter from losing the released opportunity?
π Explanation: A reservation or direct-handoff protocol assigns the released permit to the chosen waiter instead of exposing it to new arrivals. The implementation must define ownership consistently to avoid stolen permits and incorrect accounting.
Q19. A wait queue contains P and Q. A signal selects P, but P was canceled and its queue entry was not removed. What is a plausible implementation consequence?
π Explanation: A canceled waiter must be removed or detected safely before selection. Otherwise, signal may target a process that cannot resume, leaving a live waiter asleep and potentially breaking semaphore accounting.
Q20. A queue node is shared by a signal operation and another queue operation. The signaler frees the node before unlinking it safely. What is the most likely low-level risk?
π Explanation: Queue links and node lifetime must remain protected during concurrent updates. Freeing a node while another operation can still reference it creates use-after-free risks, corrupted links, lost waiters, or crashes.
Q21. A waiter checks S and sees zero. Before it is placed on the wait queue, another process signals S and finds no waiter. The first process then sleeps. What failure has occurred?
π Explanation: The signal happened after the check but before the waiter became visible in the queue. The waiter can therefore sleep after the notification has passed; check-and-enqueue must be coordinated atomically with signal.
Q22. A process holds the internal semaphore lock, discovers that it must block, and calls sleep without releasing that lock. A signaling process later needs the same lock. What can happen?
π Explanation: If the waiter sleeps while retaining the internal lock, the signaler may be unable to acquire that lock to change the state and wake it. A correct protocol releases protection as part of an atomic sleep transition.
Q23. A kernel uses a condition variable to sleep while a semaphore condition is false. After wake-up, why should the process test the condition in a loop rather than assume it is true?
π Explanation: Wake-up only makes a waiter eligible to recheck the condition. A competing process may consume the resource first, and some systems permit spurious wake-ups, so the condition must be tested again.
Q24. A semaphore uses a nonnegative count plus direct handoff. Initially one permit is free. P acquires it, Q blocks, and P signals. Which table row correctly describes the state after the signal?
π Explanation: P held the only permit, so the free count became zero after acquisition. On signal, direct handoff reserves that permit for Q; it is not exposed as a newly free count while Q waits to run.
Q25. Under a negative-count convention, S starts at 2. Three wait calls produce S = -1 with one process blocked. Two signal calls then occur. What are the final count and number of waiters?
π Explanation: The three waits yield 1, 0, and -1, placing one caller in the queue. The first signal changes S to 0 and wakes it; the second changes S to 1, leaving one free permit and no waiters.
Q26. A semaphore starts at S = 2 and uses the rule: wait decrements, blocking if negative; signal increments and wakes one waiter whenever the new value is at most zero. Three waits are followed by one signal. Which event sequence is correct?
π Explanation: The waits decrement S to 1, 0, and -1, so the third caller blocks. Signal increments the value to 0; because the result is at most zero, one queued process is awakened.
Q27. A trace records free-count values 3, 2, 1, 0, 0. At the final step a blocked process becomes ready, although the free count stays at zero. Which model best explains the trace?
π Explanation: The first three acquisitions consume the three free permits. The final zero can remain unchanged when a signal transfers a released permit directly to a blocked process instead of adding it to the free pool.
Q28. A busy-waiting semaphore is implemented with repeated ordinary reads of a shared variable. One CPU keeps seeing an old value after another CPU releases the lock. Which correction is most appropriate?
π Explanation: Unsynchronized reads may be cached, reordered, or otherwise fail to observe the release promptly. Atomic operations with appropriate memory ordering provide the visibility and ordering guarantees needed for a correct spin-based protocol.
Q29. A systems team measures two semaphore waiting strategies. Data are (wait duration ms, CPU time spent spinning ms, block-and-wake CPU overhead ms): (1,1,2); (2,2,2); (5,5,2); (10,10,2); (20,20,2). At which listed duration does blocking first use less CPU than spinning?
π Explanation: At 1 ms, spinning uses 1 ms versus 2 ms of blocking overhead; at 2 ms they are equal. At 5 ms, spinning costs 5 ms while blocking costs 2 ms, so 5 ms is the first duration favoring blocking.
Q30. A user-space semaphore uses an atomic fast path when a permit is immediately available, but enters the kernel to sleep when contention persists. What is the main benefit of this hybrid arrangement?
π Explanation: The fast path handles common uncontended operations with low overhead. When a process must wait, the kernel can block it rather than waste CPU cycles, combining efficient acquisition with proper sleep and wake-up.
Q31. A developer claims that an atomic decrement alone implements wait(S). The code decrements S and then always enters the protected data access, even when the resulting state indicates no permit. What is the exact error?
π Explanation: Atomicity protects the counter update, not the callerβs right to proceed. When the operation indicates no permit, the implementation must block or retry; entering the protected region anyway violates the resource limit.
Q32. A semaphore implementation passes tests that run only one process at a time, but fails when many processes run concurrently. Why were the original tests inadequate?
π Explanation: Serial tests rarely expose races because operations do not overlap. Concurrent executions can interleave checks, updates, queue changes, and blocking transitions in ways that reveal defects absent from single-process runs.
Q33. A trace shows a waiter checking S = 0, a signaler changing S to 1, and then the waiter entering the sleep queue without checking again. Which implementation change prevents the missed notification?
π Explanation: The check and sleep transition must be indivisible relative to signal. Otherwise, a signal can occur while no waiter is registered, after which the process sleeps despite the changed semaphore state.
Q34. A FIFO semaphore queue wakes P before Q. However, the scheduler repeatedly favors other ready tasks and delays P. Which conclusion is justified?
π Explanation: FIFO determines which waiter is chosen by signal, not when the CPU scheduler dispatches it. A separate scheduling policy can delay a ready process, so queue fairness and processor fairness are distinct.
Q35. A server uses a blocking semaphore for a resource that is usually unavailable for 50 ms. Which implementation choice best avoids wasting CPU while preserving correct permit accounting?
π Explanation: Long waits favor blocking because polling wastes processor time. The implementation must still coordinate waiter registration, release of its internal lock, and signal-side wake-up atomically enough to prevent missed notifications.
Q36. A multiprocessor implementation protects the semaphore integer with an atomic instruction but updates the linked wait queue using unprotected pointer writes. What is the most serious remaining correctness issue?
π Explanation: Atomic protection of the integer does not protect separate queue operations. Concurrent pointer updates can corrupt links or lose entries, so the count and queue must be coordinated under a complete synchronization protocol.