/* Compile with cc -Og -o thread_sleeps -pthread thread_sleeps.c */ #include #include #include #include int main(int argc, char *argv[]); void* sender(void*); void* receiver(void*); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t slept = PTHREAD_COND_INITIALIZER; int nsleeps = 0; #define NPASSES 20 int main(int argc, char *argv[]) { pthread_t sender_tid; pthread_t receiver_tid; if (pthread_create (&sender_tid, NULL, sender, NULL) != 0) { fprintf(stderr, "Couldn't create sender thread\n"); return 1; } if (pthread_create (&receiver_tid, NULL, receiver, NULL) != 0) { fprintf(stderr, "Couldn't create receiver thread\n"); return 1; } if (pthread_join (sender_tid, NULL) != 0) { fprintf(stderr, "Couldn't join with sender thread\n"); return 1; } if (pthread_join (receiver_tid, NULL) != 0) { fprintf(stderr, "Couldn't join with receiver thread\n"); return 1; } return 0; } void* sender(void* data) { int i; for (i = 0; i < NPASSES; i++) { sleep(1); printf("Sender slept %d time(s)\n", i + 1); pthread_mutex_lock(&mutex); ++nsleeps; pthread_mutex_unlock(&mutex); pthread_cond_signal(&slept); } return NULL; } void* receiver(void* data) { int total_sleeps = 1; int sleep_time; while (1) { pthread_mutex_lock(&mutex); if (nsleeps >= NPASSES) { pthread_mutex_unlock(&mutex); printf("\tReceiver saw %d total sleeps\n", total_sleeps); return NULL; } while (nsleeps < total_sleeps) { pthread_cond_wait(&slept, &mutex); } pthread_mutex_unlock(&mutex); printf("\tReceiver saw sleep number %d...", total_sleeps); ++total_sleeps; if (nsleeps < total_sleeps) { sleep_time = random() % 4; printf("sleeping %d second(s)\n", sleep_time); sleep(sleep_time); } else printf("continuing\n"); } }