/* Compile and run with something like: * gcc -Wall -g semtest.c -lpthread -o semtest * valgrind --tool=memcheck ./semtest */ #include #include #include #include #include /* we show output every N loops to show we're still alive */ #define N 500000 /* sem is used to coordinate the waiter and the poster */ sem_t sem; /* varsem is the semaphore created and destroyed */ sem_t *varsem; void *waiter(void *unused) { unsigned int count = 0; for (;;) { /* create a semaphore */ varsem = malloc(sizeof(sem_t)); sem_init(varsem, 0, 0); /* let the poster know he can post */ sem_post(&sem); /* wait for poster's post */ while (sem_wait(varsem) != 0) perror("sem_wait() in waiter"); /* destroy the semaphore */ if (sem_destroy(varsem) != 0) { perror("destroy failed"); } free(varsem); count++; if ((count % N) == 0) { printf("waiter\t%u\n", count); fflush(stdout); } } } void *poster(void *unused) { unsigned int count = 0; for (;;) { /* wait for waiter's notification that we can post varsem */ while (sem_wait(&sem) != 0) perror("sem_wait() in poster"); /* post varsem */ sem_post(varsem); count++; if ((count % N) == 0) { printf("poster\t%u\n", count); fflush(stdout); } } } int main(void) { pthread_t t1, t2; sem_init(&sem, 0, 0); printf("sem: %p\n", &sem); fflush(stdout); pthread_create(&t1, NULL, &waiter, NULL); pthread_create(&t2, NULL, &poster, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); sem_destroy(&sem); return 0; }