// // Very simple program demonstrating the use of threads. // // Command-line argument is P (number of threads). // // Each thread writes "hello" message to standard output, using // a global lock variable to be sure only one at a time is // performing output. // #include #include // has exit(), etc. #include // has usleep() #include // has pthread_ routines // declaration for function to be executed by each thread void * printHello(void * threadArg); // ---- Global variables --------------------------------------------- // (Global variables are a bit ugly, but this is an easy way to create // a variable all threads can access.) pthread_mutex_t outputLock; // ---- 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]); // Create lock. pthread_mutex_init(&outputLock, NULL); // Set up IDs for threads (need a separate variable for each // since they're shared among 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) pthread_create(&threads[i], NULL, printHello, (void *) &threadIDs[i]); // Wait for all threads to complete. for (int i = 0; i < P; ++i) pthread_join(threads[i], NULL); // Free lock resources. pthread_mutex_destroy(&outputLock); // Clean up and exit. delete [] threadIDs; delete [] threads; cout << "That's all, folks!\n"; return EXIT_SUCCESS; } // ---- Code to be executed by each thread --------------------------- // pre: *threadArg is an integer "thread ID". // post: "hello" message printed to standard output. // return value is null pointer. void * printHello(void * threadArg) { int * myID = (int *) threadArg; pthread_mutex_lock(&outputLock); cout << "hello, world, "; // pointless pause, included to make the effects of // synchronization (or lack thereof) more obvious usleep(10); cout << "from thread " << *myID << endl; pthread_mutex_unlock(&outputLock); pthread_exit((void *) NULL); }