/* ******************************************************** * * Two threads alternate synchronously. * Silvia Figueira -- Winter 09 * ******************************************************** */ #include #include /* * global variables */ pthread_mutex_t mp; pthread_cond_t cp1; pthread_cond_t cp2; pthread_t th1; pthread_t th2; /* * functions */ void *ping_pong(void *arg); /* * main */ int main(int argc, char *argv[]) { int i; pthread_mutex_init (&mp, NULL); pthread_cond_init (&cp1, NULL); pthread_cond_init (&cp2, NULL); pthread_create (&th1, NULL, ping_pong, (void *) 1); pthread_create (&th2, NULL, ping_pong, (void *) 2); pthread_join (th1, NULL); pthread_join (th2, NULL); } /* * ping_pong */ void *ping_pong (void *arg) { int th_id = (int)arg; char dummy; if (th_id == 1) { printf ("Start!\n"); scanf ("%c", &dummy); } while (1) { if (th_id == 1) { /* * thread 1 - executes first */ printf ("Thread %d\n", th_id); sleep (3); pthread_cond_signal (&cp2); pthread_mutex_lock (&mp); pthread_cond_wait (&cp1, &mp); pthread_mutex_unlock (&mp); } else { /* * thread 2 - executes second */ pthread_mutex_lock (&mp); pthread_cond_wait (&cp2, &mp); pthread_mutex_unlock (&mp); printf ("Thread %d\n", th_id); sleep (3); pthread_cond_signal (&cp1); } } }