// // Very simple program demonstrating the use of threads. // // Command-line argument is P (number of threads). // // Each thread writes "hello" message to standard output, with // no attempt to synchronize. Output will likely be garbled. // #include #include // has exit(), etc. #include // has pthread_ routines // ---- Code to be executed by each thread --------------------------- void * printHello(void * threadArg) { int * myID = (int *) threadArg; cout << "Hello from thread " << *myID << endl; return NULL; } // ---- Main program ------------------------------------------------- int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " numThreads\n"; exit(EXIT_FAILURE); } int P = atoi(argv[1]); // Set up IDs for threads. int * threadIDs = new int[P]; for (int i = 0; i < P; ++i) threadIDs[i] = i; // Start P new threads. pthread_t * threads = new pthread_t[P]; for (int i = 0; i < P; ++i) { if (pthread_create(&threads[i], NULL, printHello, (void *) &threadIDs[i]) != 0) cerr << "Unable to create thread " << i << endl; } // Wait for all threads to complete. for (int i = 0; i < P; ++i) { if (pthread_join(threads[i], NULL) != 0) cerr << "Unable to perform join on thread " << i << endl; } cout << "That's all, folks!\n"; return EXIT_SUCCESS; }