1 CANCELLATION(5)       Standards, Environments, and Macros      CANCELLATION(5)
   2 
   3 
   4 
   5 NAME
   6        cancellation - overview of concepts related to POSIX thread
   7        cancellation
   8 
   9 DESCRIPTION
  10 
  11        +-------------------------+-----------------------------------------------------+
  12        |        FUNCTION         |                       ACTION                        |
  13        +-------------------------+-----------------------------------------------------+
  14        |pthread_cancel()         | Cancels thread execution.                           |
  15        |pthread_setcancelstate() | Sets the cancellation state of a thread.            |
  16        |pthread_setcanceltype()  | Sets the cancellation type of a thread.             |
  17        |pthread_testcancel()     | Creates a cancellation point in the calling thread. |
  18        |pthread_cleanup_push()   | Pushes a cleanup handler routine.                   |
  19        |pthread_cleanup_pop()    | Pops a cleanup handler routine.                     |
  20        +-------------------------+-----------------------------------------------------+
  21 
  22    Cancellation
  23        Thread cancellation allows a thread to terminate the execution of  any
  24        application thread in the process. Cancellation is useful when further
  25        operations of one or more threads are undesirable or unnecessary.
  26 
  27 
  28        An example of a situation that could benefit from using cancellation is
  29        an asynchronously-generated cancel condition such as a user requesting
  30        to close or exit some running operation. Another example is the
  31        completion of a task undertaken by a number of threads, such as solving
  32        a maze. While many threads search for the solution, one of the threads
  33        might solve the puzzle while the others continue to operate. Since they
  34        are serving no purpose at that point, they should all be canceled.
  35 
  36    Planning Steps
  37        Planning and programming for most cancellations follow this pattern:
  38 
  39            1.     Identify which threads you want to cancel, and insert
  40                   pthread_cancel(3C) statements.
  41 
  42            2.     Identify system-defined cancellation points where a thread
  43                   that might be canceled could have changed system or program
  44                   state that should be restored.  See the Cancellation Points
  45                   for a list.
  46 
  47            3.     When a thread changes the system or program state just
  48                   before a cancellation point, and should restore that state
  49                   before the thread is canceled, place a cleanup handler
  50                   before the cancellation point with pthread_cleanup_push(3C).
  51                   Wherever a thread restores the changed state, pop the
  52                   cleanup handler from the cleanup stack with
  53                   pthread_cleanup_pop(3C).
  54 
  55            4.     Know whether the threads you are canceling call into cancel-
  56                   unsafe libraries, and disable cancellation with
  57                   pthread_setcancelstate(3C) before the call into the library.
  58                   See Cancellation State and Cancel-Safe.
  59 
  60            5.     To cancel a thread in a procedure that contains no
  61                   cancellation points, insert your own cancellation points
  62                   with pthread_testcancel(3C). This function creates
  63                   cancellation points by testing for pending cancellations and
  64                   performing those cancellations if they are found. Push and
  65                   pop cleanup handlers around the cancellation point, if
  66                   necessary (see Step 3, above).
  67 
  68    Cancellation Points
  69        The system defines certain points at which cancellation can occur
  70        (cancellation points), and you can create additional cancellation
  71        points in your application with pthread_testcancel().
  72 
  73 
  74        The following cancellation points are  defined by the system (system-
  75        defined cancellation points): creat(2), aio_suspend(3C), close(2),
  76        creat(2), getmsg(2), getpmsg(2), lockf(3C), mq_receive(3C),
  77        mq_send(3C), msgrcv(2), msgsnd(2), msync(3C), nanosleep(3C), open(2),
  78        pause(2), poll(2), pread(2), pthread_cond_timedwait(3C),
  79        pthread_cond_wait(3C), pthread_join(3C), pthread_testcancel(3C),
  80        putmsg(2), putpmsg(2), pwrite(2), read(2), readv(2), select(3C),
  81        sem_wait(3C), sigpause(3C), sigwaitinfo(3C), sigsuspend(2),
  82        sigtimedwait(3C), sigwait(2), sleep(3C), sync(2), system(3C),
  83        tcdrain(3C), usleep(3C), wait(3C), waitid(2), wait3(3C), waitpid(3C),
  84        write(2), writev(2), and  fcntl(2), when specifying F_SETLKW as the
  85        command.
  86 
  87 
  88        When cancellation is asynchronous, cancellation can occur at any time
  89        (before, during, or after the execution of the function defined as the
  90        cancellation point). When cancellation is deferred (the default case),
  91        cancellation occurs only within the scope of a function defined as a
  92        cancellation point (after the function is called and before the
  93        function returns). See Cancellation Type for more information about
  94        deferred and asynchronous cancellation.
  95 
  96 
  97        Choosing where to place cancellation points and understanding how
  98        cancellation affects your program depend upon your understanding of
  99        both your application and of cancellation mechanics.
 100 
 101 
 102        Typically, any call that might require a long wait should be a
 103        cancellation point.  Operations need to check for pending cancellation
 104        requests when the operation is about to block indefinitely. This
 105        includes threads waiting in pthread_cond_wait() and
 106        pthread_cond_timedwait(), threads waiting for the termination of
 107        another thread in pthread_join(), and threads blocked on sigwait().
 108 
 109 
 110        A mutex is explicitly not a cancellation point and should be held for
 111        only the minimal essential time.
 112 
 113 
 114        Most of the dangers in performing cancellations deal with properly
 115        restoring invariants and freeing shared resources. For example, a
 116        carelessly canceled thread might leave a mutex in a locked state,
 117        leading to a deadlock. Or it might leave a region of memory allocated
 118        with no way to identify it and therefore no way to free it.
 119 
 120    Cleanup Handlers
 121        When a thread is canceled, it should release resources and clean up the
 122        state that is shared with other threads. So, whenever a thread that
 123        might be canceled changes the state of the system or of the program, be
 124        sure to push a cleanup handler with pthread_cleanup_push(3C) before the
 125        cancellation point.
 126 
 127 
 128        When a thread is canceled, all the currently-stacked cleanup handlers
 129        are executed in last-in-first-out (LIFO) order. Each handler is run in
 130        the scope in which it was pushed. When the last cleanup handler
 131        returns, the thread-specific data destructor functions are called.
 132        Thread execution terminates when the last destructor function returns.
 133 
 134 
 135        When, in the normal course of the program, an uncanceled thread
 136        restores state that it had previously changed, be sure to pop the
 137        cleanup handler (that you had set up where the change took place) using
 138        pthread_cleanup_pop(3C).  That way, if the thread is canceled later,
 139        only currently-changed state will be restored by the handlers that are
 140        left in the stack.
 141 
 142 
 143        The pthread_cleanup_push() and pthread_cleanup_pop() functions can be
 144        implemented as macros. The application must ensure that they appear as
 145        statements, and in pairs within the same lexical scope (that is, the
 146        pthread_cleanup_push() macro can be thought to expand to a token list
 147        whose first token is '{' with pthread_cleanup_pop() expanding to a
 148        token list whose last token is the corresponding '}').
 149 
 150 
 151        The effect of the use of return, break, continue, and goto to
 152        prematurely leave a code block described by a pair of
 153        pthread_cleanup_push() and pthread_cleanup_pop() function calls is
 154        undefined.
 155 
 156    Cancellation State
 157        Most programmers will use only the default cancellation state of
 158        PTHREAD_CANCEL_ENABLE, but can choose to change the state by using
 159        pthread_setcancelstate(3C), which determines whether a thread is
 160        cancelable at all. With the default state of PTHREAD_CANCEL_ENABLE,
 161        cancellation is enabled and the thread is cancelable at points
 162        determined by its cancellation type. See Cancellation Type.
 163 
 164 
 165        If the state is PTHREAD_CANCEL_DISABLE, cancellation is disabled, the
 166        thread is not cancelable at any point, and all cancellation requests to
 167        it are held pending.
 168 
 169 
 170        You might want to disable cancellation before a call to a cancel-unsafe
 171        library, restoring the old cancel state when the call returns from the
 172        library.  See  Cancel-Safe for explanations of cancel safety.
 173 
 174    Cancellation Type
 175        A thread's cancellation type is set with pthread_setcanceltype(3C), and
 176        determines whether the thread can be canceled anywhere in its execution
 177        or only at cancellation points.
 178 
 179 
 180        With the default type of  PTHREAD_CANCEL_DEFERRED, the thread is
 181        cancelable only at cancellation points, and then only when cancellation
 182        is enabled.
 183 
 184 
 185        If the type is PTHREAD_CANCEL_ASYNCHRONOUS, the thread is cancelable at
 186        any point in its execution (assuming, of course, that cancellation is
 187        enabled). Try to limit regions of asynchronous cancellation to
 188        sequences with no external dependencies that could result in dangling
 189        resources or unresolved state conditions. Using asynchronous
 190        cancellation is discouraged because of the danger involved in trying to
 191        guarantee correct cleanup handling at absolutely every point in the
 192        program.
 193 
 194 
 195 
 196 
 197        +------------------------------+------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
 198        |Cancellation Type/State Table |                                                                                                            |                                                                                                                                                         |
 199        |Type                          | State                                                                                                      |                                                                                                                                                         |
 200        |                              | Enabled (Default)                                                                                          | Disabled                                                                                                                                                |
 201        +------------------------------+------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
 202        |Deferred (Default)            | Cancellation occurs when the target thread reaches a cancellation point and a cancel is pending. (Default) | All cancellation requests to the target thread are held pending.                                                                                        |
 203        |Asynchronous                  | Receipt of a pthread_cancel() call causes immediate cancellation.                                          | All cancellation requests to the target thread are held pending; as soon as cancellation is re-enabled, pending cancellations are executed immediately. |
 204        +------------------------------+------------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
 205 
 206    Cancel-Safe
 207        With the arrival of POSIX cancellation, the Cancel-Safe level has been
 208        added to the list of MT-Safety levels. See attributes(5). An
 209        application or library is Cancel-Safe whenever it has arranged for
 210        cleanup handlers to restore system or program state wherever
 211        cancellation can occur. The application or library is specifically
 212        Deferred-Cancel-Safe when it is Cancel-Safe for threads whose
 213        cancellation type is PTHREAD_CANCEL_DEFERRED. See Cancellation State.
 214        It is specifically Asynchronous-Cancel-Safe when it is Cancel-Safe for
 215        threads whose cancellation type is PTHREAD_CANCEL_ASYNCHRONOUS.
 216 
 217 
 218        It is easier to arrange for deferred cancel safety, as this requires
 219        system and program state protection only around cancellation points. In
 220        general, expect that most applications and libraries are not
 221        Asynchronous-Cancel-Safe.
 222 
 223    POSIX Threads Only
 224        The cancellation functions described in this manual page are available
 225        for POSIX threads, only (the Solaris threads interfaces do not provide
 226        cancellation functions).
 227 
 228 EXAMPLES
 229        Example 1 Cancellation example
 230 
 231 
 232        The following short C++ example shows the pushing/popping of
 233        cancellation handlers, the disabling/enabling of cancellation, the use
 234        of pthread_testcancel(), and so on. The free_res() cancellation handler
 235        in this example is a dummy function that simply prints a message, but
 236        that would free resources in a real application. The function f2() is
 237        called from the main thread, and goes deep into its call stack by
 238        calling itself recursively.
 239 
 240 
 241 
 242        Before f2() starts running, the newly created thread has probably
 243        posted a cancellation on the main thread since the main thread calls
 244        thr_yield() right after creating thread2.  Because cancellation was
 245        initially disabled in the main thread, through a call to
 246        pthread_setcancelstate(), the call to f2() from  main() continues and
 247        constructs X at each recursive call,  even though the main thread has a
 248        pending cancellation.
 249 
 250 
 251 
 252        When f2() is called for the fifty-first time (when "i == 50"), f2()
 253        enables cancellation by calling pthread_setcancelstate(). It then
 254        establishes a cancellation point for itself by calling
 255        pthread_testcancel(). (Because a cancellation is pending, a call to a
 256        cancellation point such as  read(2) or  write(2) would also cancel the
 257        caller here.)
 258 
 259 
 260 
 261        After the main() thread is canceled at the fifty-first iteration, all
 262        the cleanup handlers that were pushed are called in sequence; this is
 263        indicated by the calls to  free_res() and the calls to the destructor
 264        for X. At each level, the C++ runtime calls the destructor for X and
 265        then the cancellation handler,  free_res(). The print messages from
 266        free_res() and X's destructor show the sequence of calls.
 267 
 268 
 269 
 270        At the end, the main thread is joined by thread2. Because the main
 271        thread was canceled, its return status from  pthread_join() is
 272        PTHREAD_CANCELED. After the status is printed, thread2 returns, killing
 273        the  process (since it is the last thread in the process).
 274 
 275 
 276          #include <pthread.h>
 277          #include <sched.h>
 278          extern "C" void thr_yield(void);
 279 
 280          extern "C" void printf(...);
 281 
 282          struct X {
 283                  int x;
 284                  X(int i){x = i; printf("X(%d) constructed.\n", i);}
 285                  ~X(){ printf("X(%d) destroyed.\n", x);}
 286          };
 287 
 288          void
 289          free_res(void *i)
 290          {
 291                  printf("Freeing `%d`\n",i);
 292          }
 293 
 294          char* f2(int i)
 295          {
 296                  try {
 297                  X dummy(i);
 298                  pthread_cleanup_push(free_res, (void *)i);
 299                  if (i == 50) {
 300                         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
 301                      pthread_testcancel();
 302                  }
 303                  f2(i+1);
 304                  pthread_cleanup_pop(0);
 305                  }
 306                  catch (int) {
 307                  printf("Error: In handler.\n");
 308                  }
 309                  return "f2";
 310          }
 311 
 312          void *
 313          thread2(void *tid)
 314          {
 315                  void *sts;
 316 
 317                  printf("I am new thread :%d\n", pthread_self());
 318 
 319                  pthread_cancel((pthread_t)tid);
 320 
 321                  pthread_join((pthread_t)tid, &sts);
 322 
 323                  printf("main thread cancelled due to %d\n", sts);
 324 
 325                  return (sts);
 326          }
 327 
 328          main()
 329          {
 330                  pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
 331                  pthread_create(NULL, NULL, thread2, (void *)pthread_self());
 332                  thr_yield();
 333                  printf("Returned from %s\n",f2(0));
 334          }
 335 
 336 
 337 ATTRIBUTES
 338        See attributes(5) for descriptions of the following attributes:
 339 
 340 
 341 
 342 
 343        +---------------+-----------------+
 344        |ATTRIBUTE TYPE | ATTRIBUTE VALUE |
 345        +---------------+-----------------+
 346        |MT-Level       | MT-Safe         |
 347        +---------------+-----------------+
 348 
 349 SEE ALSO
 350        read(2), sigwait(2), write(2), Intro(3), condition(5),
 351        pthread_cleanup_pop(3C), pthread_cleanup_push(3C), pthread_exit(3C),
 352        pthread_join(3C), pthread_setcancelstate(3C),
 353        pthread_setcanceltype(3C), pthread_testcancel(3C), setjmp(3C),
 354        attributes(5), standards(5)
 355 
 356 
 357 
 358                                 October 4, 2005                CANCELLATION(5)