/* * This example base on code from: * B. Nichols, D. Buttlar, and J. Proulx Farrell, "Pthreads Programming," * O'reilly, 1996. * */ #include #include #define TCOUNT 10 #define WATCH_COUNT 12 void watch_count(int *); void inc_count(int *); int count = 0; pthread_mutex_t count_mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_threshold_cv = PTHREAD_COND_INITIALIZER; int thread_ids[3] = {0,1,2}; int main (int argc, char **argv) { int i; pthread_t threads[3]; pthread_attr_t custom_sched_attr; /* set scheduling policy to system so braindead solaris doesn't run threads sequentially */ pthread_attr_init(&custom_sched_attr); pthread_attr_setscope(&custom_sched_attr,PTHREAD_SCOPE_SYSTEM); /* start threads */ pthread_create(&threads[0], &custom_sched_attr, (void *) inc_count, (void *) &thread_ids[0]); pthread_create(&threads[1], &custom_sched_attr, (void *) inc_count, (void *) &thread_ids[1]); pthread_create(&threads[2], &custom_sched_attr, (void *) watch_count, (void *) &thread_ids[2]); /* wait for threads to complete */ for (i = 0; i < 3; i++) { pthread_join(threads[i],NULL); } return 0; } void watch_count(int *idp) { pthread_mutex_lock(&count_mutex); printf("watch_count(): Starting thread %d, count is %d\n",*idp, count); while(count < WATCH_COUNT) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): Thread %d, count is %d\n",*idp, count); } pthread_mutex_unlock(&count_mutex); } void inc_count(int *idp) { int i,j,x; x = 1; for (i = 0; i < TCOUNT; i++) { pthread_mutex_lock(&count_mutex); count++; printf("inc_count(): Thread %d, old count %d, new count %d\n",*idp, count -1, count); if (count == WATCH_COUNT) pthread_cond_signal(&count_threshold_cv); pthread_mutex_unlock(&count_mutex); /* do some work to allow another thread to run */ for (j = 0; j < 10000000; j++) x = x + i; } }