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