#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#define THREAD_COUNT 64
#define TEXT "barnacles"
#define TEXT_N "barnacles\n"
void run_threads(void (*)(void *), void *);
static pthread_rwlock_t start;
static void (*real_func)(void *);
static void *
thread(void *arg)
{
int r;
if ((r = pthread_rwlock_rdlock(&start)))
errc(1, r, "could not obtain lock in thread");
real_func(arg);
if ((r = pthread_rwlock_unlock(&start)))
errc(1, r, "could not release lock in thread");
return NULL;
}
void
run_threads(void (*func)(void *), void *arg)
{
pthread_t self, pthread[THREAD_COUNT];
int i, r;
self = pthread_self();
real_func = func;
if ((r = pthread_rwlock_init(&start, NULL)))
errc(1, r, "could not initialize lock");
if ((r = pthread_rwlock_wrlock(&start)))
errc(1, r, "could not lock lock");
for (i = 0; i < THREAD_COUNT; i++)
if ((r = pthread_create(&pthread[i], NULL, thread, arg))) {
warnc(r, "could not create thread");
pthread[i] = self;
}
if ((r = pthread_rwlock_unlock(&start)))
errc(1, r, "could not release lock");
sleep(1);
if ((r = pthread_rwlock_wrlock(&start)))
errx(1, "parent could not sync with children: %s",
strerror(r));
for (i = 0; i < THREAD_COUNT; i++)
if (! pthread_equal(pthread[i], self) &&
(r = pthread_join(pthread[i], NULL)))
warnc(r, "could not join thread");
}