/* ================================================================= Thread example: illustrate the problem with concurrent execution ================================================================= */ #include #include #include using namespace std; pthread_t tid[100]; int N = 0; pthread_mutex_t m; /* ============================================================== Global variables: 1 copy - all threads use the same variable "shared" variable ============================================================== */ void *worker(void *arg) { int i; // Local variable stored on STACK // Each threads has its own stack // Therefore: each thread has its own copy of local variable for (i = 0; i < 10000; i = i + 1) { pthread_mutex_lock( &m ); N = N + 1; // Shared N !!! pthread_mutex_unlock( &m ); } // cout << "N = " << N << endl; return(NULL); /* Thread exits (dies) */ } /* ======================= MAIN ======================= */ int main(int argc, char *argv[]) { int i, num_threads; /* ----- Check command line ----- */ if ( argc != 2 ) { cout << "Usage: " << argv[0] << " Num_Threads" << endl; exit(1); } /* ----- Get number of intervals and number of threads ----- */ num_threads = atoi(argv[1]); pthread_mutex_init( &m, NULL); /* ------ Create threads ------ */ for (i = 0; i < num_threads; i = i + 1) { if ( pthread_create(&tid[i], NULL, worker, NULL) ) { cout << "Cannot create thread" << endl; exit(1); } } for (i = 0; i < num_threads; i = i + 1) pthread_join(tid[i], NULL); cout << "N = " << N << endl << endl; }