xref: /openbsd-src/regress/lib/libpthread/pthread_specific/pthread_specific.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: pthread_specific.c,v 1.3 2003/07/31 21:48:05 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 2002 CubeSoft Communications, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistribution of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Neither the name of CubeSoft Communications, nor the names of its
13  *    contributors may be used to endorse or promote products derived from
14  *    this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
25  * USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <pthread.h>
29 #include <pthread_np.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include "test.h"
34 
35 #define NTHREADS	128
36 
37 pthread_key_t key;
38 int destroy_run = 0;
39 
40 static void *
41 run_thread(void *arg)
42 {
43 	int i;
44 
45 	CHECKe(write(STDOUT_FILENO, ".", 1));
46 	for (i = 0; i < 32767; i++) {
47 		void *p;
48 
49 		p = pthread_getspecific(key);
50 		if (p == NULL) {
51 			CHECKr(pthread_setspecific(key, pthread_self()));
52 		} else {
53 			ASSERT(p == pthread_self());
54 		}
55 		fflush(stderr);
56 	}
57 
58 	return (NULL);
59 }
60 
61 static void
62 destroy_key(void *keyp)
63 {
64 	destroy_run++;
65 }
66 
67 int
68 main(int argc, char *argv[])
69 {
70 	pthread_t threads[NTHREADS];
71 	int i;
72 
73 	CHECKr(pthread_key_create(&key, destroy_key));
74 	for (i = 0; i < NTHREADS; i++) {
75 		CHECKr(pthread_create(&threads[i], NULL, run_thread, NULL));
76 	}
77 	for (i = 0; i < NTHREADS; i++) {
78 		CHECKr(pthread_join(threads[i], NULL));
79 	}
80 	CHECKe(write(STDOUT_FILENO, "\n", 1));
81 
82 	CHECKr(pthread_key_delete(key));
83 
84 	ASSERT(destroy_run > 0);
85 
86 	SUCCEED;
87 }
88