1 /* Copyright (C) 2003-2022 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
24 static void
cleanup(void * arg)25 cleanup (void *arg)
26 {
27 /* Just for fun. */
28 if (pthread_cancel (pthread_self ()) != 0)
29 {
30 puts ("cleanup: cancel failed");
31 exit (1);
32 }
33
34 printf ("cleanup for %ld\n", (long int) arg);
35 }
36
37
38 static void *
tf(void * arg)39 tf (void *arg)
40 {
41 long int n = (long int) arg;
42
43 pthread_cleanup_push (cleanup, arg);
44
45 if (pthread_setcanceltype ((n & 1) == 0
46 ? PTHREAD_CANCEL_DEFERRED
47 : PTHREAD_CANCEL_ASYNCHRONOUS, NULL) != 0)
48 {
49 puts ("setcanceltype failed");
50 exit (1);
51 }
52
53 if (pthread_cancel (pthread_self ()) != 0)
54 {
55 puts ("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
69 static int
do_test(void)70 do_test (void)
71 {
72 pthread_attr_t at;
73
74 if (pthread_attr_init (&at) != 0)
75 {
76 puts ("attr_init failed");
77 return 1;
78 }
79
80 if (pthread_attr_setstacksize (&at, 1 * 1024 * 1024) != 0)
81 {
82 puts ("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 (&th[i], &at, tf, (void *) (long int) i) != 0)
92 {
93 puts ("create failed");
94 exit (1);
95 }
96
97 if (pthread_attr_destroy (&at) != 0)
98 {
99 puts ("attr_destroy failed");
100 return 1;
101 }
102
103 for (i = 0; i < N; ++i)
104 {
105 void *r;
106 if (pthread_join (th[i], &r) != 0)
107 {
108 puts ("join failed");
109 exit (1);
110 }
111
112 if (r != PTHREAD_CANCELED)
113 {
114 puts ("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