/* ===================================================== Thread example: intro to multi-threaded programming ===================================================== */ #include #include #include pthread_t tid[100]; void *worker(void *arg) { int i; i = pthread_self(); cout << "Hello, I am thread # " << i << 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); } cout << "Hello, I am the main thread, and my id is " << pthread_self() << endl << endl; /* ----- Get number of intervals and number of threads ----- */ num_threads = atoi(argv[1]); cout << "I will make " << num_threads << " threads now..." << endl << 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); }