//third.cc #include #include #include #include #include #include #include #include // shared memory int balance = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // a simple routine for thread execution void* func(void* which) { // lock pthread_mutex_lock( &mutex ); // get old balance int oldbalance = balance; printf( "This is thread %d. Old balance = %d\n", (int)which, oldbalance ); // randomly wait 0 to 2 seconds, simulating computation srand(time(0)); srand48(time(0)); int sleep_seconds = (int)( (float)drand48() * 4 ); sleep( sleep_seconds ); // increase balance balance = oldbalance + 1000; printf( "This is thread %d. New balance = %d\n", (int)which, balance ); // unlock pthread_mutex_unlock( &mutex ); } // main function: generates some threads int main(int argc, char *argv[]) { // get default attributes pthread_attr_t attr; pthread_attr_init(&attr); // thread creation pthread_t tid1, tid2; pthread_create(&tid1, &attr, func, (void*)1); pthread_create(&tid2, &attr, func, (void*)2); // thread join: wait till the threads finish pthread_join(tid1, NULL); pthread_join(tid2, NULL); }