🎓 BookMCQ
← Back to 4. Threads in Operating System

📝 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.
12
Easy
10
Medium
11
Hard

📝 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?

A.Terminate the entire server process immediately
B.Request cancellation and let the worker stop at a safe point after performing required cleanup ✅
C.Free every object the worker might use before sending a cancellation request
D.Leave the worker running because a disconnected client cannot affect server resource use
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.The cancellation request was successfully sent or queued, not that the target has completed termination ✅
B.The target has finished every cleanup handler and released all resources
C.The calling thread has joined the target automatically
D.Every thread in the process has received the same cancellation request
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.The operating system immediately terminates the whole process
B.The request is redirected to the thread with the highest priority
C.The target may continue until it reaches a cancellation point or otherwise checks for cancellation ✅
D.The target automatically switches to asynchronous cancellation
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.Asynchronous cancellation waits for a condition variable, while deferred cancellation stops at any instruction
B.Deferred cancellation can only be used when a thread owns no memory
C.Asynchronous cancellation is guaranteed to terminate the target before pthread_cancel() returns
D.Asynchronous cancellation may act at an unpredictable execution point, while deferred cancellation waits for a cancellation point ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.The request remains pending and can be acted upon after cancellation is reenabled, subject to the thread's cancellation type and a suitable point ✅
B.Disabling cancellation permanently changes the thread into a detached thread
C.The request is automatically delivered to another thread in the same process
D.Reenabling cancellation always terminates the thread before the next instruction
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.Cancellation disabled and asynchronous type
B.Cancellation enabled and deferred type ✅
C.Cancellation enabled and asynchronous type
D.Cancellation disabled and deferred type
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.pthread_detach()
B.pthread_join()
C.pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, ...) only
D.pthread_testcancel() ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.The target must terminate immediately because asynchronous type overrides every state setting
B.The request is converted into process termination
C.The request remains pending while cancellation is disabled; asynchronous type does not override the disabled state ✅
D.The kernel releases the target's mutex and completes the update for it
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.Calling pthread_cancel() a second time
B.Successfully joining the target with pthread_join() ✅
C.Setting the target's cancellation state to disabled from the manager
D.Waiting for one scheduler time slice after the request
💡 Difficulty: easy | ✅ Correct: B

📖 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()?

A.NULL in every implementation, regardless of cancellation
B.The return value of the thread's most recent system call
C.PTHREAD_CANCELED ✅
D.The identifier of the thread that requested cancellation
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.H3, then H2, then H1 ✅
B.H1, then H2, then H3
C.H2, then H1, then H3
D.Only H1, because a thread can have one cleanup handler
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.pthread_cleanup_pop(0) duplicates the handler and schedules it twice
B.The handler remains registered until the process exits
C.The handler is executed immediately regardless of the argument
D.The pop removes the handler without executing it, so it is no longer available for a later cancellation ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.Thread-specific-data destructors, then cleanup handlers, then termination
B.Cleanup handlers in reverse registration order, then thread-specific-data destructors, then thread termination ✅
C.Immediate termination, then cleanup handlers executed by the joining thread
D.Process-wide atexit handlers, then mutex destruction, then thread termination
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.The waiting thread reacquires the mutex before cancellation cleanup handlers are called ✅
B.The mutex is destroyed automatically before the handler runs
C.The cancellation requester becomes the mutex owner
D.The condition variable permanently disables cancellation for all waiters
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.Always set cancellation to enabled without recording its previous state
B.Keep cancellation disabled until the process exits
C.Save the previous cancellation state and restore that exact state after leaving the protected region ✅
D.Change the cancellation type to asynchronous before unlocking
💡 Difficulty: medium | ✅ Correct: C

📖 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?

A.A cleanup handler cannot call any synchronization function
B.The handler assumes ownership that may not exist; registration or state tracking must ensure it unlocks only a mutex the thread actually owns ✅
C.POSIX mutexes are automatically unlocked when a cancellation request is sent
D.A mutex can only be unlocked by the thread that requested cancellation
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.Close the descriptor from every worker as soon as any one worker is canceled
B.Duplicate the descriptor number in a TLS variable and assume that creates a separate open file description
C.Disable cancellation for every thread permanently
D.Coordinate shared-resource ownership or reference lifetime so one worker's cleanup does not close a descriptor still needed by another ✅
💡 Difficulty: medium | ✅ Correct: D

📖 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?

A.Wait for the next process-wide timer interrupt
B.Call pthread_cancel() repeatedly until the buffer becomes unused
C.Wait for confirmed worker termination, normally by joining the joinable thread ✅
D.Change the buffer to thread-local storage after the request
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.The program may contain a data race or visibility defect; use an atomic or synchronized flag with appropriate memory semantics ✅
B.A Boolean variable is guaranteed atomic and race-free on every C implementation
C.The compiler must always reload ordinary variables written by another thread
D.Cancellation flags are safe only when stored on the heap
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.Immediately after the first record is changed
B.Between individual pointer assignments inside the transaction
C.Before any rollback information has been recorded
D.After the transaction commits or rolls back and its invariants are restored ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.Increase the requester's priority and leave the blocking operation unchanged
B.Use a documented timeout, pollable wake-up, or coordinated I/O shutdown mechanism, then check cancellation safely ✅
C.Free the socket from another thread without coordinating ownership
D.Assume every network read is automatically a cancellation point on every platform
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.Terminate the worker thread for both tasks, even if it serves unrelated work
B.Ignore the queued task because it has no operating-system thread
C.Remove or mark the queued task before execution, but use a cooperative stop protocol for the running task ✅
D.Free the running task's stack from the queue manager immediately
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.Communicate end-of-stream or shutdown and wake dependent consumers so they do not wait forever ✅
B.Assume consumers detect producer termination by inspecting CPU utilization
C.Leave consumers blocked because cancellation applies only to the producer
D.Destroy the queue before consumers have stopped accessing it
💡 Difficulty: easy | ✅ Correct: A

📖 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?

A.Cancellation guarantees that the remote server rolled back the request
B.The local thread's termination proves the remote operation never happened
C.A network request cannot be processed more than once
D.The remote payment may have completed even though the worker never learned the outcome; use an idempotency or reconciliation protocol ✅
💡 Difficulty: medium | ✅ Correct: D

📖 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?

A.The request at 0 ms, with 7 ms latency
B.The request at 40 ms, with 15 ms latency ✅
C.The request at 20 ms, with 14 ms latency
D.The request at 50 ms, with 9 ms latency
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.20 ms
B.40 ms
C.41 ms ✅
D.81 ms
💡 Difficulty: easy | ✅ Correct: C

📖 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?

A.Longer intervals between safe checks correspond to larger observed maximum cancellation delays ✅
B.The response delay remains constant as the check interval increases
C.The worker always terminates before the cancellation request arrives
D.The response delay decreases whenever the interval doubles
💡 Difficulty: medium | ✅ Correct: A

📖 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?

A.16 ms
B.100 ms
C.410 ms
D.160 ms ✅
💡 Difficulty: hard | ✅ Correct: D

📖 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?

A.At 20 ms, despite cancellation being disabled
B.At the cancellation point at 55 ms, assuming cancellation remains enabled ✅
C.Immediately at 40 ms, even without a cancellation point under deferred cancellation
D.Only after the process terminates
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.The destructor runs first, followed by H1 and H2
B.H1 and H2 run simultaneously, then the thread terminates without the destructor
C.H2 runs, then H1, then the thread-specific-data destructor, followed by thread termination ✅
D.The thread terminates before any cleanup code runs
💡 Difficulty: hard | ✅ Correct: C

📖 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?

A.Use asynchronous cancellation inside the critical section and disable it elsewhere
B.Disable cancellation permanently and rely on process termination for shutdown
C.Allow cancellation between every machine instruction, including while shared invariants are broken
D.Use deferred cancellation, protect the short invariant-sensitive region, and check at safe boundaries outside it ✅
💡 Difficulty: easy | ✅ Correct: D

📖 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?

A.The error alone does not establish the task's outcome; use synchronized lifecycle state and a completion protocol to distinguish natural exit from cancellation ✅
B.The task must have completed normally, because every cancellation error means normal return
C.The task was canceled and its cleanup handlers definitely ran
D.The identifier can never be reused, so the error proves memory corruption
💡 Difficulty: hard | ✅ Correct: A

📖 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?

A.Free the cache as soon as the first worker receives a cancellation request
B.Request cancellation, allow safe cleanup, confirm every worker has stopped using the cache, and only then release the shared cache ✅
C.Cancel workers asynchronously, then reuse the cache without waiting for them
D.Let each worker free the entire cache from its own cleanup handler
💡 Difficulty: medium | ✅ Correct: B

📖 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.

🔗 Related Topics (MCQs)