#include #include #include #define ADD 1 #define SUB 2 pthread_mutex_t libpcp_lock = PTHREAD_MUTEX_INITIALIZER; int sum = 100; int tmpa; int tmpb; static void * func(void *arg) { int op; int i; if (strcmp((char *)arg, "add") == 0) op = ADD; else if (strcmp((char *)arg, "sub") == 0) op = SUB; else pthread_exit("bad arg"); for (i = 0; i < 10000; i++) { int sts; pthread_mutex_lock(&libpcp_lock); tmpb = tmpa = sum; if (op == ADD) { tmpa++; if ((i % 1000) == 0) wait(&sts); tmpb++; } else { tmpa--; if ((i % 1000) == 0) wait(&sts); tmpb--; } if (tmpa == tmpb) sum = tmpa; pthread_mutex_unlock(&libpcp_lock); } pthread_exit(NULL); } main() { pthread_t tid1; pthread_t tid2; int sts; char *msg; sts = pthread_create(&tid1, NULL, func, "add"); if (sts != 0) { printf("thread_create: tid1: sts=%d\n", sts); exit(1); } sts = pthread_create(&tid2, NULL, func, "sub"); if (sts != 0) { printf("thread_create: tid2: sts=%d\n", sts); exit(1); } pthread_join(tid1, (void *)&msg); if (msg != NULL) printf("tid1: %s\n", msg); pthread_join(tid2, (void *)&msg); if (msg != NULL) printf("tid2: %s\n", msg); if (sum == 100) { printf("Congratulations, you're in a bozo-free zone\n"); exit(0); } else { printf("Bozo! sum=%d at the end, expecting 100\n", sum); exit(1); } /*NOTREACHED*/ }