// // Very simple program demonstrating the use of threads. // // Command-line argument is P (number of threads). // // Each thread creates a string containing "hello" message and writes // it to standard output. No attempt is made to synchronize, but // by having each thread output its message in the form of a single // stream, we hope to avoid garbled output. // #include #include // has exit(), etc. #include // has pthread_ routines #include #include // has ostrstream class // ---- Code to be executed by each thread --------------------------- void * printHello(void * threadArg) { int * myID = (int *) threadArg; ostrstream messageStream; messageStream << "Hello from thread " << *myID << endl; string message = messageStream.str(); cout << message; 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; }