1 /* $OpenBSD: sem_destroy.c,v 1.1.1.1 2012/01/04 17:36:40 mpi Exp $ */ 2 /* 3 * Martin Pieuchot <mpi@openbsd.org>, 2011. Public Domain. 4 */ 5 6 #include <errno.h> 7 #include <unistd.h> 8 #include <pthread.h> 9 #include <semaphore.h> 10 #include "test.h" 11 12 int val; 13 sem_t cons_sem; 14 sem_t prod_sem; 15 16 void *producer(void *arg); 17 void *consumer(void *arg); 18 19 int 20 main(int argc, char **argv) 21 { 22 pthread_t prod_th, cons_th; 23 long counter = 4; 24 25 CHECKn(sem_destroy(&cons_sem)); 26 ASSERT(errno == EINVAL); 27 28 val = 0; 29 30 CHECKr(sem_init(&cons_sem, 0, 0)); 31 CHECKr(sem_init(&prod_sem, 0, 1)); 32 33 CHECKr(pthread_create(&prod_th, NULL, producer, &counter)); 34 CHECKr(pthread_create(&cons_th, NULL, consumer, &counter)); 35 36 CHECKr(pthread_join(prod_th, NULL)); 37 CHECKr(pthread_join(cons_th, NULL)); 38 39 pthread_exit(NULL); 40 41 CHECKr(sem_destroy(&prod_sem)); 42 CHECKr(sem_destroy(&cons_sem)); 43 44 SUCCEED; 45 } 46 47 void * 48 producer(void *arg) 49 { 50 long *counter = arg; 51 int i; 52 53 for (i = 0; i < *counter; i++) { 54 sem_wait(&prod_sem); 55 val++; 56 sem_post(&cons_sem); 57 } 58 59 return (NULL); 60 } 61 62 void * 63 consumer(void *arg) 64 { 65 long *counter = arg; 66 int i; 67 68 for (i = 0; i < *counter; i++) { 69 sem_wait(&cons_sem); 70 val--; 71 sem_post(&prod_sem); 72 } 73 74 return (NULL); 75 } 76