#include #include #include #define LOOP 20000 int toggle = 0; /* either 0 or 1 */ pthread_mutex_t mutex; /* protects 'toggle' */ pthread_cond_t cond; /* for the threads to wait on */ void *ping(void *arg) { int i; int rv; rv = pthread_mutex_lock(&mutex); if (rv) { fprintf(stderr, "pthread_mutex_lock failed: %d\n", rv); exit(1); } for (i = 0; i < LOOP; i++) { while (toggle == 0) { rv = pthread_cond_wait(&cond, &mutex); if (rv) { fprintf(stderr, "pthread_cond_wait failed: %d\n", rv); exit(1); } } toggle--; rv = pthread_cond_signal(&cond); if (rv) { fprintf(stderr, "pthread_cond_signal failed: %d\n", rv); exit(1); } } rv = pthread_mutex_unlock(&mutex); if (rv) { fprintf(stderr, "pthread_mutex_unlock failed: %d\n", rv); exit(1); } return NULL; } void *pong(void *arg) { int i; int rv; rv = pthread_mutex_lock(&mutex); if (rv) { fprintf(stderr, "pthread_mutex_lock failed: %d\n", rv); exit(1); } for (i = 0; i < LOOP; i++) { while (toggle == 1) { rv = pthread_cond_wait(&cond, &mutex); if (rv) { fprintf(stderr, "pthread_cond_wait failed: %d\n", rv); exit(1); } } toggle++; rv = pthread_cond_signal(&cond); if (rv) { fprintf(stderr, "pthread_cond_signal failed: %d\n", rv); exit(1); } } rv = pthread_mutex_unlock(&mutex); if (rv) { fprintf(stderr, "pthread_mutex_unlock failed: %d\n", rv); exit(1); } return NULL; } int main() { pthread_attr_t attr; pthread_t t1, t2; int rv; rv = pthread_mutex_init(&mutex, NULL); if (rv) { fprintf(stderr, "pthread_mutex_init failed: %d\n", rv); exit(1); } rv = pthread_cond_init(&cond, NULL); if (rv) { fprintf(stderr, "pthread_cond_init failed: %d\n", rv); exit(1); } rv = pthread_attr_init(&attr); if (rv) { fprintf(stderr, "pthread_attr_init failed: %d\n", rv); exit(1); } rv = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); if (rv) { fprintf(stderr, "pthread_attr_setdetachstate failed: %d\n", rv); exit(1); } rv = pthread_create(&t1, &attr, ping, NULL); if (rv) { fprintf(stderr, "pthread_create failed: %d\n", rv); exit(1); } rv = pthread_create(&t2, &attr, pong, NULL); if (rv) { fprintf(stderr, "pthread_create failed: %d\n", rv); exit(1); } rv = pthread_join(t1, NULL); if (rv) { fprintf(stderr, "pthread_join failed: %d\n", rv); exit(1); } rv = pthread_join(t2, NULL); if (rv) { fprintf(stderr, "pthread_join failed: %d\n", rv); exit(1); } return 0; }