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