Cancelling a thread

One thread can cancel a sibling thread in its own task before that thread completes its program. The graceful way to do this is to call the CancelWaitAndPostException() member function of the target thread's thread handle. In response, the target thread unblocks if it is blocked and throws an exception (TCancelWaitException). If the thread is not blocked when the exception is posted, the exception will be thrown the next time the thread blocks.

If your thread executes a compute loop that does not call any functions that can block, the loop can call the thread's CheckForPendingCancel() member function to poll for a posted exception:

      // get a handle on our own thread
      TThreadHandle thisThread(TThreadHandle::kUseSelf);
      
      while (condition) {
          // compute...
          try {
              thisThread.CheckForPendingCancel();
          }
          catch (const TCancelWaitException&) {
              // handle exception...
          }
      }
If CheckForPendingCancel() detects a pending cancel exception, it throws the exception immediately. Your thread must define an appropriate way to handle the exception.

CancelWaitAndPostException() does not guarantee that the target thread has thrown the exception before CancelWaitAndPostException() returns to its caller; the caller can make no assumptions about the exception's timing.


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker