/* ================================================================= Thread example: illustrate the problem with concurrent execution ================================================================= */ #include #include #include int N; pthread_t tid[100]; void *worker(void *arg) { int i; for (i = 0; i < 10000; i = i + 1) { N = N + 1; } cout << "Added 10000 to 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]); N = 0; cout << "Setting N to 0" << endl; /* ------ 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; }