📝 Process synchronization in Linux (36 MCQs)
Linux Kernel and User-Space Synchronization Facilities
Linux synchronization mechanisms coordinate concurrent tasks accessing shared kernel structures, process memory, and system resources. The kernel provides mutexes, spinlocks, read-write locks, completions, wait queues, and read-copy-update mechanisms for different execution contexts. User-space applications commonly use POSIX threading primitives backed by futex support, allowing efficient coordination between threads and processes.
Why Linux Requires Context-Specific Locking Mechanisms
Kernel code executes in different contexts, including process context, interrupt context, and preemptible execution. A lock suitable for a sleeping process may be unsafe inside an interrupt handler. Linux therefore provides synchronization primitives with different blocking and execution rules, allowing developers to protect shared structures without violating kernel scheduling constraints.
Mutexes, Spinlocks, Futexes, and Wait Queues
Kernel mutexes allow tasks to sleep while waiting, whereas spinlocks make a task repeatedly check until the lock becomes available. Read-write locks support multiple readers or an exclusive writer. Wait queues coordinate event-based blocking, and completions signal operation completion. In user space, futex operations support efficient synchronization with kernel assistance when contention requires waiting.
Two Kernel Tasks Competing for a Shared Structure
Suppose kernel tasks T1 and T2 need to update the same protected data structure in process context. T1 acquires a kernel mutex and performs its update. T2 attempts the same lock and sleeps rather than continuously consuming CPU time. When T1 releases the mutex, T2 becomes eligible to continue its protected operation.
Lock Selection, Interrupt Safety, and Kernel Performance
Linux synchronization supports efficient kernel execution, shared-memory applications, and concurrent file and device operations. Mutexes suit sleeping contexts, while spinlocks protect short critical sections where sleeping is prohibited. Incorrect primitive selection can cause deadlocks or interrupt-related problems. Lock contention, memory ordering, and excessive spinning can also reduce scalability on multiprocessor systems.
Misconceptions About Linux Synchronization Primitives
'A kernel spinlock allows its holder to sleep' is incorrect because sleeping while holding a spinlock is generally prohibited. 'A futex is simply a user-space mutex' is incorrect because it is a kernel-supported waiting mechanism. 'All Linux locks work identically' is incorrect because they differ in ownership, blocking, context, and usage rules.
Exam Focus: Comparing Linux Kernel and User-Space Locks
Distinguish mutexes, spinlocks, read-write locks, completions, wait queues, and futexes by their purposes and execution contexts. Explain why sleeping locks cannot be used indiscriminately in interrupt context. Questions may examine lock contention, user-space synchronization, atomic operations, and suitable primitives for short versus long critical sections.
Key Terms of Linux Synchronization
- Kernel mutex - Sleeping mutual-exclusion primitive.
- Spinlock - Busy-waiting kernel lock.
- Futex - Fast user-space locking support.
- Wait queue - Structure for blocked kernel tasks.
- Completion - Mechanism signalling operation completion.
- RCU - Read-copy-update synchronization technique.
📝 All Process synchronization in Linux MCQs
Q1. A kernel task in process context requests a mutex that is already held by another task. What is the normal behavior?
📖 Explanation: A kernel mutex can put a contending task to sleep, allowing another task to run while the lock is held. This avoids wasting CPU cycles that a busy-wait loop would consume.
Q2. A developer calls a potentially blocking kernel mutex operation from an interrupt handler. Which review finding identifies the central error?
📖 Explanation: A kernel mutex may sleep while waiting for ownership, so taking it from interrupt context can invoke an illegal scheduling operation. Interrupt handlers need synchronization that is safe in that execution context.
Q3. Which statement best describes the waiting behavior of a kernel spinlock?
📖 Explanation: A spinlock protects a short critical section by making a competing CPU wait actively until the owner releases it. This avoids sleep and wake-up overhead but consumes processor cycles while contested.
Q4. A kernel routine holds a lock while waiting for a disk read to finish. Which redesign is usually more appropriate when the routine may sleep?
📖 Explanation: A kernel mutex is suitable when the protected operation can sleep because blocked tasks can be scheduled out. A spinlock held across disk I/O wastes CPU and violates the no-sleep rule.
Q5. A process-context routine and a local interrupt handler use the same spinlock. What should the process-context code consider to prevent the interrupt from spinning forever on a lock held by the interrupted code?
📖 Explanation: If an interrupt handler on the same CPU can request a spinlock already held by interrupted code, it can spin forever because the owner cannot resume. Saving and disabling local interrupts around acquisition prevents that self-deadlock.
Q6. A kernel data structure is read by many tasks but modified infrequently. Which primitive directly supports concurrent readers while excluding writers?
📖 Explanation: Read locks allow multiple readers to inspect protected data concurrently, while a write lock excludes both other writers and readers. This suits read-heavy structures that require consistent updates. Writers still retain exclusive access.
Q7. A read-write lock has R1 holding a read lock from time 0 to 4 and R2 holding a read lock from time 1 to 6. Writer W requests access at time 2, and R3 requests a read lock at time 3. Under a policy that admits no new readers once W is queued, when can W acquire the write lock? Treat the trace as: R1 0–4; R2 1–6; W requests 2; R3 requests 3.
📖 Explanation: R1 and R2 overlap until R2 releases at time 6. Because the stated policy blocks later readers while W is queued, the writer can acquire at time 6, not when R1 exits at time 4.
Q8. A kernel task sleeps on a wait queue until a device buffer becomes ready. The producer calls wake_up(), but the buffer is still not ready when the task runs. What must the task do?
📖 Explanation: A wake-up only makes a waiting task eligible to run; it does not make the event predicate true. The task must recheck the condition before proceeding with protected data. Recheck before using the buffer.
Q9. A kernel routine checks a wait condition, releases its lock, and only afterward registers itself as a waiter. A producer can update the condition and wake the queue between those steps. What failure can occur?
📖 Explanation: A correct wait-queue protocol registers the waiter and checks the condition in a coordinated sequence before sleeping. This prevents the producer from signaling between an unprotected check and waiter registration.
Q10. A kernel worker calls wait_for_completion(), but another task calls complete() before the worker begins waiting. What should the worker normally experience?
📖 Explanation: Linux completions retain a done state until consumed by a waiter. Therefore, signaling before the wait does not lose the completion; the later waiter can continue immediately. without requiring another signal.
Q11. A driver must stop several worker tasks after a shutdown event. Which completion operation is most appropriate when every current waiter and later waiter should observe the completed state until reinitialization?
📖 Explanation: complete_all marks the completion done for all current and future waiters until it is reinitialized. It is suited to a one-time shutdown or initialization event, not a counted work queue.
Q12. A monitoring graph reports waiter count and completed operations at each time: time 0: waiters 1, completions 0; time 1: waiters 2, completions 0; time 2: waiters 4, completions 0; time 3: waiters 6, completions 0; time 4: waiters 7, completions 0; time 5, after an external timeout: waiters 3, completions 4. What is the strongest conclusion supported by the data?
📖 Explanation: The waiter count rises while completed work remains at zero, then completions resume after external intervention. This indicates blocked progress, but the graph alone cannot prove a specific deadlock cycle.
Q13. Why can a mutex implementation built on Linux futexes avoid a system call when there is no contention?
📖 Explanation: Futex-based libraries usually attempt atomic user-space acquisition first. The kernel is involved when a thread must actually sleep or wake waiters, reducing system-call overhead when the lock is uncontended. during ordinary uncontended acquisition.
Q14. A thread calls FUTEX_WAIT with an expected value of 1, but the futex word currently contains 2. What should happen?
📖 Explanation: FUTEX_WAIT compares the futex word with the expected value before blocking. Since the current value is 2 rather than 1, the wait does not sleep and typically reports EAGAIN. rather than sleeping on a changed value.
Q15. Two Linux processes map the same shared-memory region at different virtual addresses and use a futex word located inside it. Why can they still coordinate?
📖 Explanation: A process-shared futex identifies a shared memory location, not an identical virtual address. Different mappings can point to the same physical location, allowing separate processes to coordinate using one futex word.
Q16. A performance graph lists lock-contention level and futex system calls per 1,000 acquisitions: (0,0), (1,3), (2,45), (3,210), (4,490). Which interpretation best fits the trend?
📖 Explanation: As contention rises, more acquisitions require kernel-assisted waiting, so syscall frequency increases. The graph shows the cost of leaving the uncontended user-space fast path, not an increase in lock correctness.
Q17. A Linux thread calls sem_wait(), but a signal interrupts the operation before it acquires a permit. The operation is still required. What is the correct response when errno is EINTR?
📖 Explanation: EINTR means the wait was interrupted before a permit was acquired. When the operation remains necessary, the program should handle the error and retry rather than assuming success or posting a permit.
Q18. Which POSIX semaphore operation is specified as async-signal-safe and can therefore be used by a signal handler to notify a waiting thread?
📖 Explanation: POSIX defines sem_post as async-signal-safe, so it can notify a waiting thread from a signal handler. This does not make arbitrary shared-data updates in that handler safe. when used from asynchronous handler context.
Q19. A parent and child created with fork() each update a normal global variable protected by separately initialized process-private mutexes. Why can their updates still conflict from the application's perspective?
📖 Explanation: After fork, ordinary writable memory is separate through copy-on-write, and independently created private mutexes are distinct objects. Interprocess coordination therefore requires genuinely shared memory and a synchronization object common to both processes.
Q20. A process calls sem_unlink() on a named semaphore while two other processes still have it open. What is the usual effect?
📖 Explanation: sem_unlink removes the semaphore name from the namespace, preventing future opens by that name. Processes that already hold open references can continue using the object until those references are closed.
Q21. An unnamed POSIX semaphore must coordinate a parent and child process after fork(). Which setup is required?
📖 Explanation: Setting pshared nonzero is not enough if each process has a separate copy. The unnamed semaphore must reside at a shared memory location that every participant maps as the same object.
Q22. A worker obtains a permit from a POSIX semaphore and then exits without posting it. What can happen to the resource pool?
📖 Explanation: A POSIX semaphore counts permits but does not normally track which process owns each permit. If a worker exits without posting, the count can remain reduced and strand later requests.
Q23. A robust process-shared mutex reports that its previous owner died while holding it. What should the new owner do before using the protected data?
📖 Explanation: A robust mutex can report owner death to the next acquirer, but it cannot repair application data. The new owner must validate or recover the protected state before marking it consistent.
Q24. A process uses an advisory file lock to coordinate access to a shared file. Which distinction from a pthread mutex is correct?
📖 Explanation: File locks coordinate access according to a file's locking interface and are useful across independently running programs. A pthread mutex instead protects memory shared by threads or processes using that object.
Q25. A main thread must wait until a joinable worker has terminated before reading its result. Which Pthreads operation most directly provides that synchronization point?
📖 Explanation: pthread_join waits for the specified joinable thread to terminate and can collect its return value. It establishes actual completion instead of relying on a guessed sleep duration. before the caller reads the result.
Q26. A barrier is initialized for four participating threads. Only three reach pthread_barrier_wait(), while the fourth exits early. What happens to the three arrivals under normal barrier behavior?
📖 Explanation: A barrier releases participants only after the configured arrival count is reached. With four participants configured and only three arriving, the three remain blocked unless the design handles the missing participant.
Q27. A thread locks a normal non-recursive mutex, calls a function that attempts to lock the same mutex again, and then waits indefinitely. What is the likely explanation?
📖 Explanation: A normal mutex is not designed for recursive acquisition by its owner. Re-locking it can deadlock, while the precise behavior depends on the mutex type and interface rules; code needing recursion must explicitly select and understand an appropriate recursive mutex.
Q28. A worker may be canceled while holding a mutex. Which design requirement is most important?
📖 Explanation: Cancellation does not generally repair protected application data or guarantee automatic mutex release. Cleanup logic must reflect actual ownership, release locks safely, and account for any partially applied update before other threads use the state.
Q29. A developer marks a shared integer volatile and assumes that concurrent increments are atomic. Which assessment is correct?
📖 Explanation: Volatile affects certain compiler access assumptions but does not make a read-modify-write indivisible or establish interthread synchronization. Use a C atomic operation or a suitable lock for shared increments. or publish unrelated shared state.
Q30. Two threads update the same counter using atomic fetch-add with relaxed memory ordering. Which guarantee does this operation provide?
📖 Explanation: Relaxed fetch-add makes the increment indivisible and orders modifications to that atomic object. It does not create a release-acquire relationship for unrelated data, so publication requires additional ordering. for any associated shared data.
Q31. Thread A initializes a data structure and then performs a release-store to an atomic ready flag. Thread B uses an acquire-load and observes that released value. What does this establish?
📖 Explanation: A release-store orders earlier writes before publication, and an acquire-load that reads that value establishes synchronization. Consequently, the reader can observe the initialized data that preceded the release. when the acquire observes that release.
Q32. A developer argues that a shared counter needs no synchronization on a single-core Linux system because only one thread executes at an instant. Why is this reasoning incorrect?
📖 Explanation: Even on one CPU, the scheduler can preempt a thread between separate load, increment, and store instructions. Another thread can update the same old value, causing one increment to be lost.
Q33. What is the central purpose of an RCU read-side critical section?
📖 Explanation: RCU read-side sections identify periods when readers may hold references to shared data. An updater can publish a replacement while existing readers finish without forcing every reader through a conventional lock.
Q34. An RCU updater removes a node from a shared list and immediately frees its memory. A reader may already have obtained a pointer before removal. What is the correct repair?
📖 Explanation: Removing a node prevents new readers from finding it, but existing readers may still hold references. synchronize_rcu waits for the pre-existing read-side sections to finish before the node is freed.
Q35. A performance graph reports throughput and lock-wait percentage as worker count increases: (1,100,1), (2,190,4), (4,350,12), (8,365,48), (16,360,76). What is the best interpretation?
📖 Explanation: Throughput stops improving while wait time rises as worker count grows. This pattern suggests serialization around the shared lock; adding threads increases contention rather than useful parallel work. as contention continues to rise.
Q36. Three kernel tasks create this dependency cycle: T1 holds A and requests C; T2 holds B and requests A; T3 holds C and requests B. Which policy directly prevents this lock-order pattern in future code?
📖 Explanation: The requests form a cycle: T1 holds A and needs C, T2 holds B and needs A, and T3 holds C and needs B. Enforcing A-before-B-before-C acquisition breaks that circular-wait pattern.