/* *************************************************** * Print the 5th. * One thread reads numbers from the keyboard. * One of two other threads outputs every 5th number. * * Silvia Figueira -- Winter 09 * *************************************************** */ #include #include /* * global variables */ int number = 0; int counter = 0; int flag = 0; pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cp = PTHREAD_COND_INITIALIZER; /* * functions */ void *read_number(void *arg); void *print_number(void *arg); /* * main */ int main() { int i; pthread_t th1, th2, th3; pthread_mutex_init (&mp, NULL); pthread_cond_init (&cp, NULL); pthread_create (&th1, NULL, read_number, (void *)NULL); pthread_create (&th2, NULL, print_number, (void *) (void *)2); pthread_create (&th3, NULL, print_number, (void *) (void *)3); pthread_join (th1, NULL); pthread_join (th2, NULL); pthread_join (th3, NULL); } /* * read numbers */ void *read_number (void *arg) { int lnumber; while (1) { scanf ("%d", &lnumber); pthread_mutex_lock (&mp); counter++; number = lnumber; if ((counter % 5) == 0) flag = 1; pthread_mutex_unlock (&mp); if ((counter % 5) == 0) pthread_cond_signal (&cp); } } /* * print numbers */ void * print_number (void *arg) { int id = (int)arg; while (1) { printf ("Waiting...\n"); pthread_mutex_lock (&mp); /* * Use the flag to make sure only one thread prints */ while (!flag) { pthread_cond_wait (&cp, &mp); } flag = 0; printf ("Thread %d: %d ==> %d\n", id, counter, number); pthread_mutex_unlock (&mp); } }