📝 Thread cancellation in operating system (33 MCQs)
Terminating a Thread Before Normal Completion
Thread cancellation is a mechanism that requests the termination of a thread before it completes its assigned work. It belongs to thread lifecycle management and is useful when an operation becomes unnecessary, a request is abandoned, or an application is shutting down. Cancellation may be implemented cooperatively through safe cancellation points or asynchronously through immediate cancellation, depending on the threading interface.
Why Applications Need Controlled Thread Termination
Background threads may continue consuming CPU time, memory, and other resources after their results are no longer needed. Simply terminating execution without cleanup can leave locks held, shared data inconsistent, or resources unreleased. Cancellation mechanisms provide ways to stop unnecessary work while allowing applications to establish appropriate cleanup and resource-management procedures.
Deferred and Asynchronous Cancellation Procedures
In deferred cancellation, a target thread responds to a cancellation request at defined cancellation points where cleanup can be performed safely. In asynchronous cancellation, termination may occur at almost any point during execution, making resource safety difficult. POSIX Pthreads supports cancellation controls, cancellation points, cleanup handlers, and functions such as pthread_cancel().
Canceling a Worker Waiting for Network Data
Suppose a worker thread waits for data from a network connection after a client abandons its request. The application requests cancellation using pthread_cancel(). Under deferred cancellation, the worker responds when it reaches an eligible cancellation point. Registered cleanup handlers can release acquired resources and close relevant application-managed connections before termination.
Resource Cleanup, Deadlock Risks, and Cancellation Safety
Deferred cancellation offers safer resource management because threads can respond at controlled execution points. It supports servers, background jobs, and interactive applications. Asynchronous cancellation can leave mutexes locked or data structures inconsistent. Even deferred cancellation requires careful cleanup design because a thread may terminate while holding resources or between related operations.
Misconceptions About Canceling Running Threads
'pthread_cancel() always terminates the target immediately' is incorrect because deferred cancellation waits for an appropriate cancellation point. 'Cancellation automatically releases every application resource' is incorrect because cleanup actions may be required. 'Asynchronous cancellation is always safer because it is faster' is incorrect because it can interrupt critical operations unpredictably.
Exam Focus: Deferred Cancellation and Cleanup Handlers
Compare deferred and asynchronous cancellation by timing, safety, and resource-management implications. Trace a cancellation request through an eligible cancellation point and cleanup handler. Questions may examine pthread_cancel(), cancellation state and type, resource release, mutex ownership, and why cooperative termination is generally preferred for complex applications.
Key Terms of Thread Cancellation
- Cancellation - Requested termination of a thread.
- Deferred cancellation - Termination at safe cancellation points.
- Asynchronous cancellation - Termination at arbitrary execution points.
- Cancellation point - Location where cancellation is checked.
- Cleanup handler - Function releasing required resources.
- pthread_cancel() - Requests POSIX thread cancellation.
📝 All Thread cancellation in operating system MCQs
Q1. A web server is processing a large request when the client disconnects and the result is no longer useful. Which response stops unnecessary work while protecting shared resources?
📖 Explanation: A deferred request lets the worker stop at a controlled point, release resources it owns, and preserve shared invariants. The server avoids needless computation without assuming that requesting cancellation has already ended execution.
Q2. A manager calls pthread_cancel() for a worker. What does a successful return from this function establish?
📖 Explanation: pthread_cancel() requests cancellation of the specified thread. Its successful return reports that the request was queued; the target may still need to reach a cancellation point, run cleanup handlers, and terminate.
Q3. A POSIX thread uses deferred cancellation. A request arrives while it performs a long computation containing no cancellation points or explicit checks. What is the likely behavior?
📖 Explanation: With deferred cancellation enabled, a pending request is acted upon at a cancellation point. A computation that never reaches one can therefore remain active, so long-running loops need deliberate safe opportunities to check.
Q4. Which statement best distinguishes asynchronous cancellation from deferred cancellation in POSIX threads?
📖 Explanation: Asynchronous cancellation permits termination at an unpredictable point, whereas deferred cancellation waits for a defined cancellation point. The latter generally gives application code a better opportunity to preserve invariants and clean up.
Q5. A worker disables cancellation before a critical update, then restores it afterward. A student says a pending request is discarded while cancellation is disabled. Which correction is right?
📖 Explanation: The flawed step is treating disabled cancellation as cancellation-request deletion. The request remains pending; restoring the prior enabled state allows it to be acted upon according to the thread's cancellation type and execution points.
Q6. In the POSIX thread model described by the Linux manual, what are the default cancellation settings for a newly created thread?
📖 Explanation: New POSIX threads normally begin with cancellation enabled and the deferred type. Thus, a cancellation request can be acted upon at a cancellation point unless the thread changes its state or type.
Q7. A CPU-bound worker wants to remain responsive to deferred cancellation but has no blocking library calls inside its processing loop. Which POSIX operation can create an explicit cancellation check?
📖 Explanation: pthread_testcancel() tests for a pending cancellation request and acts as an explicit cancellation point when cancellation is enabled. Placing it at safe loop boundaries improves responsiveness without permitting interruption inside invariant-sensitive operations.
Q8. A thread has asynchronous cancellation type but has disabled cancellation state. Another thread calls pthread_cancel() while it is updating a shared object. What should happen at that moment?
📖 Explanation: Cancellation state determines whether a request may currently be acted upon; type determines when it is acted upon once enabled. Therefore, disabled state keeps the request pending even when the selected type is asynchronous.
Q9. A thread manager must reclaim a buffer only after the canceled worker can no longer access it. Which lifecycle operation provides the normal POSIX confirmation for a joinable target?
📖 Explanation: A cancellation request is asynchronous with respect to its caller. For a joinable thread, pthread_join() waits for termination and collects its exit status, giving the manager a reliable point after which target-owned resources can be reclaimed.
Q10. A canceled POSIX thread has completed its cancellation sequence. What value is made available as its exit status to a successful pthread_join()?
📖 Explanation: After cancellation has been acted upon and the target terminates, a successful join obtains PTHREAD_CANCELED as its exit status. This distinguishes cancellation from an ordinary return value supplied by the thread routine.
Q11. A thread registers cleanup handlers H1, then H2, then H3, and is canceled while all three remain registered. In what order are they invoked?
📖 Explanation: Cleanup handlers are maintained as a stack. Cancellation pops and invokes them in last-in, first-out order, so H3 executes first, followed by H2 and then H1, before thread-specific-data destructors run.
Q12. A student registers a cleanup handler with pthread_cleanup_push() and later calls pthread_cleanup_pop(0) before normal return. The student expects the handler to run during a later cancellation. What is wrong?
📖 Explanation: The incorrect assumption is that popping always preserves a handler. pthread_cleanup_pop(0) removes the top handler without executing it; that handler is no longer registered and will not run during a later cancellation.
Q13. When POSIX cancellation is acted upon, which sequence describes the principal cleanup stages?
📖 Explanation: The cancellation sequence first invokes stacked cleanup handlers in reverse registration order, then invokes thread-specific-data destructors, and finally terminates the thread. The joining thread observes completion afterward, not by running cleanup itself.
Q14. A worker is canceled while blocked in pthread_cond_wait() and has a cleanup handler that unlocks the associated mutex. What does POSIX require before that handler is called?
📖 Explanation: A condition wait is a cancellation point. When cancellation is acted upon there, the waiting thread reacquires the associated mutex before cleanup handlers run, allowing a correctly designed handler to unlock a mutex it owns.
Q15. A worker disables cancellation while holding a mutex, updates a shared record, unlocks the mutex, and reenables cancellation. Which practice makes this pattern safer when cancellation settings may already have been changed by the caller?
📖 Explanation: Unconditionally enabling cancellation can overwrite a state established by an outer scope. Saving and restoring the previous state preserves nested control correctly, while keeping the disabled interval short and ensuring the mutex is released first.
Q16. A cleanup handler always calls pthread_mutex_unlock(), but the worker may be canceled before it successfully acquires that mutex. What is the design flaw?
📖 Explanation: The flawed step is assuming the mutex is owned on every cancellation path. If cancellation occurs before acquisition, unconditional unlocking is invalid; cleanup registration and ownership tracking must match the actual lock state.
Q17. A canceled worker's cleanup handler closes a file descriptor that is also being used by another worker. What should the application change?
📖 Explanation: A file descriptor used by several workers has shared lifetime requirements. Cleanup should release only resources the target can relinquish; reference counting or synchronized ownership prevents one canceled worker from invalidating another worker's active use.
Q18. A controller requests cancellation and immediately frees a buffer that the worker may still be reading. Which action should occur before the buffer is reclaimed?
📖 Explanation: Sending a request does not prove the worker has stopped. The controller should wait for confirmed termination, commonly with pthread_join(), before freeing memory that the target might still access or modify.
Q19. Two threads access an ordinary shared Boolean cancellation flag; one writes it while the other reads it without synchronization. A test run appears correct. What is the sound assessment?
📖 Explanation: The flawed reasoning treats a successful test as proof of thread safety. Unsynchronized conflicting accesses can create a data race or visibility problem; an atomic or properly synchronized flag is needed.
Q20. A worker updates several related database records as one logical transaction. At which boundary is deferred cancellation generally safest?
📖 Explanation: Cancellation should occur when the related updates form a consistent state. A committed or rolled-back transaction boundary avoids leaving only part of the logical operation applied and reduces recovery ambiguity.
Q21. A network worker may block indefinitely in a read operation, while its cancellation flag is checked only after the read returns. Which improvement best addresses delayed cancellation?
📖 Explanation: A flag cannot be checked while execution is indefinitely blocked. A timeout or explicit wake-up strategy lets the worker regain control, inspect cancellation safely, and release resources without relying on undocumented behavior.
Q22. A thread pool receives cancellation for one queued task and one already-running task. Which handling correctly distinguishes their states?
📖 Explanation: A queued task has not begun execution and can often be removed or marked canceled. A running task needs cooperation at safe boundaries; terminating its reusable worker could disrupt unrelated jobs.
Q23. A producer is canceled while consumers wait on a bounded queue that will receive no more items. What must a correct shutdown protocol also do?
📖 Explanation: Canceling the producer does not automatically notify consumers that no further items will arrive. A shutdown marker or equivalent signal must wake them and define whether remaining queue items are drained or discarded.
Q24. A worker sends a payment request, then is canceled before receiving the server's response. Why is blindly retrying the payment unsafe?
📖 Explanation: Thread cancellation stops local execution but cannot undo a remote side effect. The payment may already have completed, so retries need an idempotency key or status reconciliation to avoid duplicate charges.
Q25. A graph gives cancellation request and confirmed completion offsets in milliseconds: (0,7); (10,18); (20,34); (30,35); (40,55); (50,59). For which request is the cancellation latency greatest?
📖 Explanation: Latency is completion offset minus request offset. The six differences are 7, 8, 14, 5, 15, and 9 milliseconds, so the request at 40 ms actually has the maximum latency of 15 milliseconds.
Q26. A graph plots the maximum observed cancellation delay against the interval between safe checks: (5,6); (10,11); (20,21); (40,41); (80,81). What delay is shown when checks are 40 ms apart?
📖 Explanation: Read the point whose first coordinate is 40. Its second coordinate is 41, so the plotted maximum cancellation delay is 41 milliseconds for a 40-millisecond interval between checks in this measured workload.
Q27. A runtime records (safe-check interval in ms, observed maximum response delay in ms): (4,5); (8,9); (16,17); (32,33); (64,65). Which trend is supported by these observations?
📖 Explanation: Each plotted delay is one millisecond greater than its check interval. The observations therefore show increasing response delay as safe checks become less frequent, although they do not establish a universal timing guarantee.
Q28. A worker receives a cancellation request at 14:02:10.250 and confirmed termination occurs at 14:02:10.410. What is the cancellation response latency?
📖 Explanation: Subtract request time from completion time: 10.410 seconds minus 10.250 seconds equals 0.160 seconds. Therefore, the measured cancellation response latency is 160 milliseconds, including the target response and its cleanup time.
Q29. A thread has cancellation disabled from time 0 through time 40 ms. A request arrives at 20 ms, cancellation is reenabled at 40 ms, and the next deferred cancellation point occurs at 55 ms. When can the request be acted upon?
📖 Explanation: The request remains pending while cancellation is disabled. Reenabling at 40 ms makes it eligible, but deferred cancellation waits for the next cancellation point, which occurs at 55 ms; it is not immediate at 40 ms.
Q30. A canceled thread has cleanup handlers H1 then H2 registered and a thread-specific-data value with a destructor. Which sequence is correct?
📖 Explanation: Cleanup handlers execute in reverse registration order, so H2 precedes H1. After those handlers finish, thread-specific-data destructors are invoked, and the thread then terminates with a canceled exit status available to a successful join.
Q31. A developer wants cancellation to be delayed during a short critical section but responsive during the rest of the worker's life. Which policy is most appropriate?
📖 Explanation: Deferred cancellation allows the worker to choose safe stopping boundaries. Protecting invariant-sensitive operations and checking between bounded units balances responsiveness with consistent shared state and reduces the risk of abrupt interruption.
Q32. A manager marks a task as canceling, but the task may finish naturally at the same time. A late pthread_cancel() attempt reports that no such thread exists. What should the manager infer?
📖 Explanation: A failed request, such as an invalid or absent thread identifier, does not identify why the task ended. The manager must rely on synchronized lifecycle tracking and a valid completion result rather than infer the outcome from the error alone.
Q33. Several workers share a cache, and cancellation may arrive while any worker is using an entry. Which shutdown order best prevents use-after-free and incomplete cleanup?
📖 Explanation: The cache must remain valid while any worker can access it. Request cancellation, wait for workers to finish cleanup and confirm completion, then release shared storage to avoid use-after-free and inconsistent state.