/* * This example base on code from: * B. Nichols, D. Buttlar, and J. Proulx Farrell, "Pthreads Programming," * O'reilly, 1996. * */ #include #include void do_another_thing(int *); void do_one_thing(int *); void do_wrap_up(int, int); int r1 = 0, r2 = 0, r3 = 0; pthread_mutex_t r3_mutex=PTHREAD_MUTEX_INITIALIZER; int main (int argc, char **argv) { pthread_t thread1, thread2; 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); r3 = 34; /* start two threads */ pthread_create(&thread1, &custom_sched_attr, (void *) do_one_thing, (void *) &r1); pthread_create(&thread2, &custom_sched_attr, (void *) do_another_thing, (void *) &r2); /* wait till threads complete */ pthread_join(thread1,NULL); pthread_join(thread2,NULL); /* print results */ do_wrap_up(r1,r2); return 0; } void do_one_thing(int *pnum_times) { int i,j,x; /* protect access to r3 */ pthread_mutex_lock(&r3_mutex); if (r3 >0) { x = r3; r3 --; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (i = 0; i < 4;i++) { printf("doing one thing\n"); for (j = 0; j < 10000000; j++) x = x + i; (*pnum_times)++; } } void do_another_thing(int *pnum_times) { int i,j,x; /* protect access to r3 */ pthread_mutex_lock(&r3_mutex); if (r3 >0) { x = r3; r3 --; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (i = 0; i < 4;i++) { printf("doing another thing\n"); for (j = 0; j < 10000000; j++) x = x + i; (*pnum_times)++; } } void do_wrap_up(int first, int second) { int total; total = first+second; printf("Wrap up: one thing %d, another %d, total %d, r3 %d\n", first,second, total, r3); }