1/* Copyright (C) 2003-2024 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
17
18#include <pthread.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22
23
24static void
25cleanup (void *arg)
26{
27 /* Just for fun. */
28 if (pthread_cancel (th: pthread_self ()) != 0)
29 {
30 puts (s: "cleanup: cancel failed");
31 exit (1);
32 }
33
34 printf (format: "cleanup for %ld\n", (long int) arg);
35}
36
37
38static void *
39tf (void *arg)
40{
41 long int n = (long int) arg;
42
43 pthread_cleanup_push (cleanup, arg);
44
45 if (pthread_setcanceltype (type: (n & 1) == 0
46 ? PTHREAD_CANCEL_DEFERRED
47 : PTHREAD_CANCEL_ASYNCHRONOUS, NULL) != 0)
48 {
49 puts (s: "setcanceltype failed");
50 exit (1);
51 }
52
53 if (pthread_cancel (th: pthread_self ()) != 0)
54 {
55 puts (s: "cancel failed");
56 exit (1);
57 }
58
59 pthread_testcancel ();
60
61 /* We should never come here. */
62
63 pthread_cleanup_pop (0);
64
65 return NULL;
66}
67
68
69static int
70do_test (void)
71{
72 pthread_attr_t at;
73
74 if (pthread_attr_init (attr: &at) != 0)
75 {
76 puts (s: "attr_init failed");
77 return 1;
78 }
79
80 if (pthread_attr_setstacksize (attr: &at, stacksize: 1 * 1024 * 1024) != 0)
81 {
82 puts (s: "attr_setstacksize failed");
83 return 1;
84 }
85
86#define N 20
87 int i;
88 pthread_t th[N];
89
90 for (i = 0; i < N; ++i)
91 if (pthread_create (newthread: &th[i], attr: &at, start_routine: tf, arg: (void *) (long int) i) != 0)
92 {
93 puts (s: "create failed");
94 exit (1);
95 }
96
97 if (pthread_attr_destroy (attr: &at) != 0)
98 {
99 puts (s: "attr_destroy failed");
100 return 1;
101 }
102
103 for (i = 0; i < N; ++i)
104 {
105 void *r;
106 if (pthread_join (th: th[i], thread_return: &r) != 0)
107 {
108 puts (s: "join failed");
109 exit (1);
110 }
111
112 if (r != PTHREAD_CANCELED)
113 {
114 puts (s: "thread not canceled");
115 exit (1);
116 }
117 }
118
119 return 0;
120}
121
122
123#define TEST_FUNCTION do_test ()
124#include "../test-skeleton.c"
125

source code of glibc/sysdeps/pthread/tst-cancel10.c