#ifndef THREADMGR_H_ #define THREADMGR_H_ #include // has pthread_ routines // ---- Class for "thread manager" to manage groups of threads ------- // (Caveat reader: This class represents a first attempt at writing // a class to create and manage POSIX threads. Experience with its // use might suggest improvements to the design and implementation.) // ThreadObj must be a class that defines: // type "ptr" to itself // method "run" containing code for thread to execute, with // signature void run(void) template class threadManager { private: typedef typename ThreadObj::ptr tObjPtr; public: // Constructor. // pre: objs is an array of nThreads pointers to ThreadObj // objects, properly initialized. // post: threads have been constructed and started for all // objects. threadManager(const int nThreads, tObjPtr objs[]) { numThreads = nThreads; threads = new pthread_t[numThreads]; for (int i = 0; i < numThreads; ++i) pthread_create(&threads[i], NULL, doRun, (void *) objs[i]); } // Destructor. ~threadManager(void) { delete [] threads; } // Wait for all threads to complete. void join(void) { for (int i = 0; i < numThreads; ++i) pthread_join(threads[i], NULL); } private: // Make copy constructor and assignment operator private // so they can't be used (since it's not clear this would // make sense). threadManager(const threadManager & t); threadManager & operator= (const threadManager & t); // Wrapper for thread object's "run" method. static void * doRun(void * argPtr) { tObjPtr objPtr = (tObjPtr) argPtr; objPtr->run(); pthread_exit((void *) NULL); } // Member variables. int numThreads; // number of threads pthread_t * threads; // "handles" for threads }; #endif // THREADMGR_H_