local.h revision 1.2
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 <stdlib.h> 19#include <string.h> 20#include <unistd.h> 21#include <pthread.h> 22 23#define THREAD_COUNT 64 24 25#define TEXT "barnacles" 26#define TEXT_N "barnacles\n" 27 28void run_threads(void (*)(void *), void *); 29 30static pthread_rwlock_t start; 31static void (*real_func)(void *); 32 33static void * 34thread(void *arg) 35{ 36 int r; 37 38 if ((r = pthread_rwlock_rdlock(&start))) 39 errx(1, "could not obtain lock in thread: %s", strerror(r)); 40 real_func(arg); 41 if ((r = pthread_rwlock_unlock(&start))) 42 errx(1, "could not release lock in thread: %s", strerror(r)); 43 return NULL; 44} 45 46void 47run_threads(void (*func)(void *), void *arg) 48{ 49 pthread_t self, pthread[THREAD_COUNT]; 50 int i, r; 51 52 self = pthread_self(); 53 real_func = func; 54 if ((r = pthread_rwlock_init(&start, NULL))) 55 errx(1, "could not initialize lock: %s", strerror(r)); 56 57 if ((r = pthread_rwlock_wrlock(&start))) /* block */ 58 errx(1, "could not lock lock: %s", strerror(r)); 59 60 for (i = 0; i < THREAD_COUNT; i++) 61 if ((r = pthread_create(&pthread[i], NULL, thread, arg))) { 62 warnx("could not create thread: %s", strerror(r)); 63 pthread[i] = self; 64 } 65 66 67 if ((r = pthread_rwlock_unlock(&start))) /* unleash */ 68 errx(1, "could not release lock: %s", strerror(r)); 69 70 sleep(1); 71 72 if ((r = pthread_rwlock_wrlock(&start))) /* sync */ 73 errx(1, "parent could not sync with children: %s", 74 strerror(r)); 75 76 for (i = 0; i < THREAD_COUNT; i++) 77 if (! pthread_equal(pthread[i], self) && 78 (r = pthread_join(pthread[i], NULL))) 79 warnx("could not join thread: %s", strerror(r)); 80} 81 82