xref: /openbsd-src/regress/lib/libc/stdio_threading/include/local.h (revision 5054e3e78af0749a9bb00ba9a024b3ee2d90290f)
1 /*
2  * Copyright (c) 2008 Bret S. Lambert <blambert@openbsd.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #include <stdio.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <pthread.h>
21 
22 #define THREAD_COUNT 64
23 
24 #define TEXT	"barnacles"
25 #define	TEXT_N	"barnacles\n"
26 
27 void	run_threads(void (*)(void *), void *);
28 
29 static pthread_rwlock_t	start;
30 static void	(*real_func)(void *);
31 
32 static void *
33 thread(void *arg)
34 {
35 	int	r;
36 
37 	if ((r = pthread_rwlock_rdlock(&start)))
38 		errx(1, "could not obtain lock in thread: %s", strerror(r));
39 	real_func(arg);
40 	if ((r = pthread_rwlock_unlock(&start)))
41 		errx(1, "could not release lock in thread: %s", strerror(r));
42 	return NULL;
43 }
44 
45 void
46 run_threads(void (*func)(void *), void *arg)
47 {
48 	pthread_t	self, pthread[THREAD_COUNT];
49 	int	i, r;
50 
51 	self = pthread_self();
52 	real_func = func;
53 	if ((r = pthread_rwlock_init(&start, NULL)))
54 		errx(1, "could not initialize lock: %s", strerror(r));
55 
56 	if ((r = pthread_rwlock_wrlock(&start)))		/* block */
57 		errx(1, "could not lock lock: %s", strerror(r));
58 
59 	for (i = 0; i < THREAD_COUNT; i++)
60 		if ((r = pthread_create(&pthread[i], NULL, thread, arg))) {
61 			warnx("could not create thread: %s", strerror(r));
62 			pthread[i] = self;
63 		}
64 
65 
66 	if ((r = pthread_rwlock_unlock(&start)))		/* unleash */
67 		errx(1, "could not release lock: %s", strerror(r));
68 
69 	sleep(1);
70 
71 	if ((r = pthread_rwlock_wrlock(&start)))		/* sync */
72 		errx(1, "parent could not sync with children: %s",
73 		    strerror(r));
74 
75 	for (i = 0; i < THREAD_COUNT; i++)
76 		if (! pthread_equal(pthread[i], self) &&
77 		    (r = pthread_join(pthread[i], NULL)))
78 			warnx("could not join thread: %s", strerror(r));
79 }
80 
81