1 .\"
   2 .\" Sun Microsystems, Inc. gratefully acknowledges The Open Group for
   3 .\" permission to reproduce portions of its copyrighted documentation.
   4 .\" Original documentation from The Open Group can be obtained online at
   5 .\" http://www.opengroup.org/bookstore/.
   6 .\"
   7 .\" The Institute of Electrical and Electronics Engineers and The Open
   8 .\" Group, have given us permission to reprint portions of their
   9 .\" documentation.
  10 .\"
  11 .\" In the following statement, the phrase ``this text'' refers to portions
  12 .\" of the system documentation.
  13 .\"
  14 .\" Portions of this text are reprinted and reproduced in electronic form
  15 .\" in the SunOS Reference Manual, from IEEE Std 1003.1, 2004 Edition,
  16 .\" Standard for Information Technology -- Portable Operating System
  17 .\" Interface (POSIX), The Open Group Base Specifications Issue 6,
  18 .\" Copyright (C) 2001-2004 by the Institute of Electrical and Electronics
  19 .\" Engineers, Inc and The Open Group.  In the event of any discrepancy
  20 .\" between these versions and the original IEEE and The Open Group
  21 .\" Standard, the original IEEE and The Open Group Standard is the referee
  22 .\" document.  The original Standard can be obtained online at
  23 .\" http://www.opengroup.org/unix/online.html.
  24 .\"
  25 .\" This notice shall appear on any product containing this material.
  26 .\"
  27 .\" The contents of this file are subject to the terms of the
  28 .\" Common Development and Distribution License (the "License").
  29 .\" You may not use this file except in compliance with the License.
  30 .\"
  31 .\" You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
  32 .\" or http://www.opensolaris.org/os/licensing.
  33 .\" See the License for the specific language governing permissions
  34 .\" and limitations under the License.
  35 .\"
  36 .\" When distributing Covered Code, include this CDDL HEADER in each
  37 .\" file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  38 .\" If applicable, add the following below this CDDL HEADER, with the
  39 .\" fields enclosed by brackets "[]" replaced with your own identifying
  40 .\" information: Portions Copyright [yyyy] [name of copyright owner]
  41 .\"
  42 .\"
  43 .\" Portions Copyright (c) 1995 IEEE.  All Rights Reserved.
  44 .\" Copyright (c) 2001, The IEEE and The Open Group.  All Rights Reserved.
  45 .\" Copyright (c) 2008, Sun Microsystems, Inc.  All Rights Reserved.
  46 .\"
  47 .TH CANCELLATION 5 "Oct 4, 2005"
  48 .SH NAME
  49 cancellation \- overview of concepts related to POSIX thread cancellation
  50 .SH DESCRIPTION
  51 .sp
  52 
  53 .sp
  54 .TS
  55 box;
  56 c | c
  57 l | l .
  58 FUNCTION        ACTION
  59 _
  60 \fBpthread_cancel()\fR  Cancels thread execution.
  61 \fBpthread_setcancelstate()\fR  Sets the cancellation \fIstate\fR of a thread.
  62 \fBpthread_setcanceltype()\fR   Sets the cancellation \fItype\fR of a thread.
  63 \fBpthread_testcancel()\fR      T{
  64 Creates a cancellation point in the calling thread.
  65 T}
  66 \fBpthread_cleanup_push()\fR    Pushes a cleanup handler routine.
  67 \fBpthread_cleanup_pop()\fR     Pops a cleanup handler routine.
  68 .TE
  69 
  70 .SS "Cancellation"
  71 .sp
  72 .LP
  73 Thread cancellation allows a thread to terminate the execution of  any
  74 application thread in the process. Cancellation is useful when further
  75 operations of one or more threads are undesirable or unnecessary.
  76 .sp
  77 .LP
  78 An example of a situation that could benefit from using cancellation is an
  79 asynchronously-generated cancel condition such as a user requesting to close or
  80 exit some running operation. Another example is the completion of a task
  81 undertaken by a number of threads, such as solving a maze. While many threads
  82 search for the solution, one of the threads might solve the puzzle while the
  83 others continue to operate. Since they are serving no purpose at that point,
  84 they should all be canceled.
  85 .SS "Planning Steps"
  86 .sp
  87 .LP
  88 Planning and programming for most cancellations follow this pattern:
  89 .RS +4
  90 .TP
  91 1.
  92 Identify which threads you want to cancel, and insert
  93 \fBpthread_cancel\fR(3C) statements.
  94 .RE
  95 .RS +4
  96 .TP
  97 2.
  98 Identify system-defined cancellation points where a thread that might be
  99 canceled could have changed system or program state that should be restored.
 100 See the \fBCancellation Points\fR for a list.
 101 .RE
 102 .RS +4
 103 .TP
 104 3.
 105 When a thread changes the system or program state just before a cancellation
 106 point, and should restore that state before the thread is canceled, place a
 107 cleanup handler before the cancellation point with
 108 \fBpthread_cleanup_push\fR(3C). Wherever a thread restores the changed state,
 109 pop the cleanup handler from the cleanup stack with
 110 \fBpthread_cleanup_pop\fR(3C).
 111 .RE
 112 .RS +4
 113 .TP
 114 4.
 115 Know whether the threads you are canceling call into cancel-unsafe
 116 libraries, and disable cancellation with \fBpthread_setcancelstate\fR(3C)
 117 before the call into the library.  See \fBCancellation State\fR and
 118 \fBCancel-Safe\fR.
 119 .RE
 120 .RS +4
 121 .TP
 122 5.
 123 To cancel a thread in a procedure that contains no cancellation points,
 124 insert your own cancellation points with \fBpthread_testcancel\fR(3C). This
 125 function creates cancellation points by testing for pending cancellations and
 126 performing those cancellations if they are found. Push and pop cleanup handlers
 127 around the cancellation point, if necessary (see Step 3, above).
 128 .RE
 129 .SS "Cancellation Points"
 130 .sp
 131 .LP
 132 The system defines certain points at which cancellation can occur (cancellation
 133 points), and you can create additional cancellation points in your application
 134 with \fBpthread_testcancel()\fR.
 135 .sp
 136 .LP
 137 The following cancellation points are  defined by the system (system-defined
 138 cancellation points): \fBcreat\fR(2), \fBaio_suspend\fR(3C), \fBclose\fR(2),
 139 \fBcreat\fR(2), \fBgetmsg\fR(2), \fBgetpmsg\fR(2), \fBlockf\fR(3C),
 140 \fBmq_receive\fR(3C), \fBmq_send\fR(3C), \fBmsgrcv\fR(2), \fBmsgsnd\fR(2),
 141 \fBmsync\fR(3C), \fBnanosleep\fR(3C), \fBopen\fR(2), \fBpause\fR(2),
 142 \fBpoll\fR(2), \fBpread\fR(2), \fBpthread_cond_timedwait\fR(3C),
 143 \fBpthread_cond_wait\fR(3C), \fBpthread_join\fR(3C),
 144 \fBpthread_testcancel\fR(3C), \fBputmsg\fR(2), \fBputpmsg\fR(2),
 145 \fBpwrite\fR(2), \fBread\fR(2), \fBreadv\fR(2), \fBselect\fR(3C),
 146 \fBsem_wait\fR(3C), \fBsigpause\fR(3C), \fBsigwaitinfo\fR(3C),
 147 \fBsigsuspend\fR(2), \fBsigtimedwait\fR(3C), \fBsigwait\fR(2), \fBsleep\fR(3C),
 148 \fBsync\fR(2), \fBsystem\fR(3C), \fBtcdrain\fR(3C), \fBusleep\fR(3C),
 149 \fBwait\fR(3C), \fBwaitid\fR(2), \fBwait3\fR(3C), \fBwaitpid\fR(3C),
 150 \fBwrite\fR(2), \fBwritev\fR(2), and  \fBfcntl\fR(2), when specifying
 151 \fBF_SETLKW\fR as the command.
 152 .sp
 153 .LP
 154 When cancellation is asynchronous, cancellation can occur at any time (before,
 155 during, or after the execution of the function defined as the cancellation
 156 point). When cancellation is deferred (the default case), cancellation occurs
 157 only within the scope of a function defined as a cancellation point (after the
 158 function is called and before the function returns). See \fBCancellation
 159 Type\fR for more information about deferred and asynchronous cancellation.
 160 .sp
 161 .LP
 162 Choosing where to place cancellation points and understanding how cancellation
 163 affects your program depend upon your understanding of both your application
 164 and of cancellation mechanics.
 165 .sp
 166 .LP
 167 Typically, any call that might require a long wait should be a cancellation
 168 point.  Operations need to check for pending cancellation requests when the
 169 operation is about to block indefinitely. This includes threads waiting in
 170 \fBpthread_cond_wait()\fR and \fBpthread_cond_timedwait()\fR, threads waiting
 171 for the termination of another thread in \fBpthread_join()\fR, and threads
 172 blocked on \fBsigwait()\fR.
 173 .sp
 174 .LP
 175 A mutex is explicitly not a cancellation point and should be held for only the
 176 minimal essential time.
 177 .sp
 178 .LP
 179 Most of the dangers in performing cancellations deal with properly restoring
 180 invariants and freeing shared resources. For example, a carelessly canceled
 181 thread might leave a mutex in a locked state, leading to a deadlock. Or it
 182 might leave a region of memory allocated with no way to identify it and
 183 therefore no way to free it.
 184 .SS "Cleanup Handlers"
 185 .sp
 186 .LP
 187 When a thread is canceled, it should release resources and clean up the state
 188 that is shared with other threads. So, whenever a thread that might be canceled
 189 changes the state of the system or of the program, be sure to push a cleanup
 190 handler with \fBpthread_cleanup_push\fR(3C) before the cancellation point.
 191 .sp
 192 .LP
 193 When a thread is canceled, all the currently-stacked cleanup handlers are
 194 executed in last-in-first-out (LIFO) order. Each handler is run in the scope in
 195 which it was pushed. When the last cleanup handler returns, the thread-specific
 196 data destructor functions are called. Thread execution terminates when the last
 197 destructor function returns.
 198 .sp
 199 .LP
 200 When, in the normal course of the program, an uncanceled thread restores state
 201 that it had previously changed, be sure to pop the cleanup handler (that you
 202 had set up where the change took place) using \fBpthread_cleanup_pop\fR(3C).
 203 That way, if the thread is canceled later, only currently-changed state will be
 204 restored by the handlers that are left in the stack.
 205 .sp
 206 .LP
 207 The \fBpthread_cleanup_push()\fR and \fBpthread_cleanup_pop()\fR functions can
 208 be implemented as macros. The application must ensure that they appear as
 209 statements, and in pairs within the same lexical scope (that is, the
 210 \fBpthread_cleanup_push()\fR macro can be thought to expand to a token list
 211 whose first token is '{' with \fBpthread_cleanup_pop()\fR expanding to a token
 212 list whose last token is the corresponding '}').
 213 .sp
 214 .LP
 215 The effect of the use of \fBreturn\fR, \fBbreak\fR, \fBcontinue\fR, and
 216 \fBgoto\fR to prematurely leave a code block described by a pair of
 217 \fBpthread_cleanup_push()\fR and \fBpthread_cleanup_pop()\fR function calls is
 218 undefined.
 219 .SS "Cancellation State"
 220 .sp
 221 .LP
 222 Most programmers will use only the default cancellation state of
 223 \fBPTHREAD_CANCEL_ENABLE\fR, but can choose to change the state by using
 224 \fBpthread_setcancelstate\fR(3C), which determines whether a thread is
 225 cancelable at all. With the default \fIstate\fR of
 226 \fBPTHREAD_CANCEL_ENABLE\fR, cancellation is enabled and the thread is
 227 cancelable at points determined by its cancellation \fItype\fR. See
 228 \fBCancellation Type\fR.
 229 .sp
 230 .LP
 231 If the \fIstate\fR is \fBPTHREAD_CANCEL_DISABLE\fR, cancellation is disabled,
 232 the thread is not cancelable at any point, and all cancellation requests to it
 233 are held pending.
 234 .sp
 235 .LP
 236 You might want to disable cancellation before a call to a cancel-unsafe
 237 library, restoring the old cancel state when the call returns from the library.
 238 See  \fBCancel-Safe\fR for explanations of cancel safety.
 239 .SS "Cancellation Type"
 240 .sp
 241 .LP
 242 A thread's cancellation \fBtype\fR is set with \fBpthread_setcanceltype\fR(3C),
 243 and determines whether the thread can be canceled anywhere in its execution or
 244 only at cancellation points.
 245 .sp
 246 .LP
 247 With the default \fItype\fR of  \fBPTHREAD_CANCEL_DEFERRED\fR, the thread is
 248 cancelable only at cancellation points, and then only when cancellation is
 249 enabled.
 250 .sp
 251 .LP
 252 If the \fItype\fR is \fBPTHREAD_CANCEL_ASYNCHRONOUS\fR, the thread is
 253 cancelable at any point in its execution (assuming, of course, that
 254 cancellation is enabled). Try to limit regions of asynchronous cancellation to
 255 sequences with no external dependencies that could result in dangling resources
 256 or unresolved state conditions. Using asynchronous cancellation is discouraged
 257 because of the danger involved in trying to guarantee correct cleanup handling
 258 at absolutely every point in the program.
 259 .sp
 260 
 261 .sp
 262 .TS
 263 box;
 264 c | c | c
 265 l | l | l .
 266 Cancellation Type/State Table
 267 Type    State
 268         Enabled (Default)       Disabled
 269 _
 270 Deferred (Default)      T{
 271 Cancellation occurs when the target thread reaches a cancellation point and a cancel is pending. (Default)
 272 T}      T{
 273 All cancellation requests to the target thread are held pending.
 274 T}
 275 Asynchronous    T{
 276 Receipt of a \fBpthread_cancel()\fR call causes immediate cancellation.
 277 T}      T{
 278 All cancellation requests to the target thread are held pending; as soon as cancellation is re-enabled, pending cancellations are executedimmediately.
 279 T}
 280 .TE
 281 
 282 .SS "Cancel-Safe"
 283 .sp
 284 .LP
 285 With the arrival of POSIX cancellation, the Cancel-Safe level has been added to
 286 the list of MT-Safety levels. See \fBattributes\fR(5). An application or
 287 library is Cancel-Safe whenever it has arranged for cleanup handlers to restore
 288 system or program state wherever cancellation can occur. The application or
 289 library is specifically Deferred-Cancel-Safe when it is Cancel-Safe for threads
 290 whose cancellation type is \fBPTHREAD_CANCEL_DEFERRED\fR. See \fBCancellation
 291 State\fR. It is specifically Asynchronous-Cancel-Safe when it is Cancel-Safe
 292 for threads whose cancellation type is \fBPTHREAD_CANCEL_ASYNCHRONOUS\fR.
 293 .sp
 294 .LP
 295 It is easier to arrange for deferred cancel safety, as this requires system and
 296 program state protection only around cancellation points. In general, expect
 297 that most applications and libraries are not Asynchronous-Cancel-Safe.
 298 .SS "POSIX Threads Only"
 299 .sp
 300 .LP
 301 The cancellation functions described in this manual page are available for
 302 POSIX threads, only (the Solaris threads interfaces do not provide cancellation
 303 functions).
 304 .SH EXAMPLES
 305 .LP
 306 \fBExample 1 \fRCancellation example
 307 .sp
 308 .LP
 309 The following short C++ example shows the pushing/popping of cancellation
 310 handlers, the disabling/enabling of cancellation, the use of
 311 \fBpthread_testcancel()\fR, and so on. The \fBfree_res()\fR cancellation
 312 handler in this example is a dummy function that simply prints a message, but
 313 that would free resources in a real application. The function \fBf2()\fR is
 314 called from the main thread, and goes deep into its call stack by calling
 315 itself recursively.
 316 
 317 .sp
 318 .LP
 319 Before \fBf2()\fR starts running, the newly created thread has probably posted
 320 a cancellation on the main thread since the main thread calls \fBthr_yield()\fR
 321 right after creating thread2.  Because cancellation was initially disabled in
 322 the main thread, through a call to \fBpthread_setcancelstate()\fR, the call to
 323 \fBf2()\fR from  \fBmain()\fR continues and constructs X at each recursive
 324 call,  even though the main thread has a pending cancellation.
 325 
 326 .sp
 327 .LP
 328 When \fBf2()\fR is called for the fifty-first time (when \fB"i == 50"\fR),
 329 \fBf2()\fR enables cancellation by calling \fBpthread_setcancelstate()\fR. It
 330 then establishes a cancellation point for itself by calling
 331 \fBpthread_testcancel()\fR. (Because a cancellation is pending, a call to a
 332 cancellation point such as  \fBread\fR(2) or  \fBwrite\fR(2) would also cancel
 333 the caller here.)
 334 
 335 .sp
 336 .LP
 337 After the \fBmain()\fR thread is canceled at the fifty-first iteration, all the
 338 cleanup handlers that were pushed are called in sequence; this is indicated by
 339 the calls to  \fBfree_res()\fR and the calls to the destructor for \fIX\fR. At
 340 each level, the C++ runtime calls the destructor for \fIX\fR and then the
 341 cancellation handler,  \fBfree_res()\fR. The print messages from
 342 \fBfree_res()\fR and \fIX\fR's destructor show the sequence of calls.
 343 
 344 .sp
 345 .LP
 346 At the end, the main thread is joined by thread2. Because the main thread was
 347 canceled, its return status from  \fBpthread_join()\fR is
 348 \fBPTHREAD_CANCELED\fR. After the status is printed, thread2 returns, killing
 349 the  process (since it is the last thread in the process).
 350 
 351 .sp
 352 .in +2
 353 .nf
 354 #include <pthread.h>
 355 #include <sched.h>
 356 extern "C" void thr_yield(void);
 357 
 358 extern "C" void printf(...);
 359 
 360 struct X {
 361         int x;
 362         X(int i){x = i; printf("X(%d) constructed.\en", i);}
 363         ~X(){ printf("X(%d) destroyed.\en", x);}
 364 };
 365 
 366 void
 367 free_res(void *i)
 368 {
 369         printf("Freeing `%d`\en",i);
 370 }
 371 
 372 char* f2(int i)
 373 {
 374         try {
 375         X dummy(i);
 376         pthread_cleanup_push(free_res, (void *)i);
 377         if (i == 50) {
 378                pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
 379             pthread_testcancel();
 380         }
 381         f2(i+1);
 382         pthread_cleanup_pop(0);
 383         }
 384         catch (int) {
 385         printf("Error: In handler.\en");
 386         }
 387         return "f2";
 388 }
 389 
 390 void *
 391 thread2(void *tid)
 392 {
 393         void *sts;
 394 
 395         printf("I am new thread :%d\en", pthread_self());
 396 
 397         pthread_cancel((pthread_t)tid);
 398 
 399         pthread_join((pthread_t)tid, &sts);
 400 
 401         printf("main thread cancelled due to %d\en", sts);
 402 
 403         return (sts);
 404 }
 405 
 406 main()
 407 {
 408         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
 409         pthread_create(NULL, NULL, thread2, (void *)pthread_self());
 410         thr_yield();
 411         printf("Returned from %s\en",f2(0));
 412 }
 413 .fi
 414 .in -2
 415 
 416 .SH ATTRIBUTES
 417 .sp
 418 .LP
 419 See \fBattributes\fR(5) for descriptions of the following attributes:
 420 .sp
 421 
 422 .sp
 423 .TS
 424 box;
 425 c | c
 426 l | l .
 427 ATTRIBUTE TYPE  ATTRIBUTE VALUE
 428 _
 429 MT-Level        MT-Safe
 430 .TE
 431 
 432 .SH SEE ALSO
 433 .sp
 434 .LP
 435 \fBread\fR(2), \fBsigwait\fR(2), \fBwrite\fR(2), \fBIntro\fR(3),
 436 \fBcondition\fR(5), \fBpthread_cleanup_pop\fR(3C),
 437 \fBpthread_cleanup_push\fR(3C), \fBpthread_exit\fR(3C), \fBpthread_join\fR(3C),
 438 \fBpthread_setcancelstate\fR(3C), \fBpthread_setcanceltype\fR(3C),
 439 \fBpthread_testcancel\fR(3C), \fBsetjmp\fR(3C), \fBattributes\fR(5),
 440 \fBstandards\fR(5)