// // 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 lock to be sure only one at a time is performing output. // In this version, we use classes to hide some of the low-level // details of multithreading and avoid global variables. // #include #include // has exit(), etc. #include // has usleep() #include "pthreads-threadmgr.h" // has threadManager class #include "pthreads-lock.h" // has lockObj class // ---- Class for thread --------------------------------------------- // See function definitions below for comments about functions. class helloThreadObj { public: typedef helloThreadObj * ptr; helloThreadObj(const int myID); void run(void); private: static lockObj outLock; // lock for output int myID; // unique ID for thread }; // ---- 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 P helloThreadObj objects, one for each thread, to // hold parameters. helloThreadObj::ptr * threadObjs = new helloThreadObj::ptr[P]; for (int i = 0; i < P; ++i) threadObjs[i] = new helloThreadObj(i); // Create and start P new threads. threadManager tMgr(P, threadObjs); // Wait for all threads to complete. tMgr.join(); // Clean up and exit. for (int i = 0; i < P; ++i) delete threadObjs[i]; delete [] threadObjs; cout << "That's all, folks!\n"; return EXIT_SUCCESS; } // ---- Functions, etc., for helloThreadObj class -------------------- // Constructor. helloThreadObj::helloThreadObj(const int myID) { this->myID = myID; } // Member function containing code each thread should execute. void helloThreadObj::run(void) { outLock.lock(); cout << "hello, world, "; // pointless pause, included to make the effects of // synchronization (or lack thereof) more obvious usleep(10); cout << "from thread " << myID << endl; outLock.unlock(); } // Initialization for static member variable. lockObj helloThreadObj::outLock;