local.h revision 1.1
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
27void	run_threads(void (*)(void *), void *);
28
29static pthread_rwlock_t	start;
30static void	(*real_func)(void *);
31
32static void *
33thread(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
45void
46run_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