1 /* Test Thread-Specific Data.
2 Copyright (C) 2000-2022 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19 #define _GNU_SOURCE
20
21 #include <pthread.h>
22 #include <assert.h>
23 #include <stdio.h>
24 #include <error.h>
25 #include <errno.h>
26
27 #define THREADS 10
28 #define KEYS 400
29
30 pthread_key_t key[KEYS];
31
32 void *
thr(void * arg)33 thr (void *arg)
34 {
35 error_t err;
36 int i;
37
38 for (i = 0; i < KEYS; i++)
39 {
40 printf ("pthread_getspecific(%d).\n", key[i]);
41 assert (pthread_getspecific (key[i]) == NULL);
42 printf ("pthread_setspecific(%d, %d).\n", key[i], pthread_self ());
43 err = pthread_setspecific (key[i], (void *) pthread_self ());
44 printf ("pthread_setspecific(%d, %d) => %d.\n", key[i], pthread_self (),
45 err);
46 assert_perror (err);
47 }
48
49 return 0;
50 }
51
52 int
main(int argc,char ** argv)53 main (int argc, char **argv)
54 {
55 error_t err;
56 int i;
57 pthread_t tid[THREADS];
58
59 void des (void *val)
60 {
61 assert ((pthread_t) val == pthread_self ());
62 }
63
64 assert (pthread_getspecific ((pthread_key_t) 0) == NULL);
65 assert (pthread_setspecific ((pthread_key_t) 0, (void *) 0x1) == EINVAL);
66
67 for (i = 0; i < KEYS; i++)
68 err = pthread_key_create (&key[i], des);
69
70 for (i = 0; i < THREADS; i++)
71 {
72 err = pthread_create (&tid[i], 0, thr, 0);
73 if (err)
74 error (1, err, "pthread_create (%d)", i);
75 }
76
77 for (i = 0; i < THREADS; i++)
78 {
79 void *ret;
80
81 err = pthread_join (tid[i], &ret);
82 if (err)
83 error (1, err, "pthread_join");
84
85 assert (ret == 0);
86 }
87
88 return 0;
89 }
90