00001 00002 // Program Name: threadpool.h 00003 // 00004 // Purpose - Thread Pool Class 00005 // 00006 // Created By : David Blain Created On : Oct. 21, 2005 00007 // Modified By : Modified On: 00008 // 00010 00011 #ifndef __THREADPOOL_H__ 00012 #define __THREADPOOL_H__ 00013 00014 #include <qstring.h> 00015 #include <qptrlist.h> 00016 #include <qmutex.h> 00017 #include <qwaitcondition.h> 00018 #include <qthread.h> 00019 00020 class ThreadPool; 00021 00024 // 00025 // 00026 // 00029 00030 class CEvent 00031 { 00032 private: 00033 00034 QMutex m_mutex; 00035 QWaitCondition m_wait; 00036 bool m_bSignaled; 00037 00038 public: 00039 00040 CEvent( bool bInitiallyOwn = FALSE ); 00041 virtual ~CEvent(); 00042 00043 bool SetEvent (); 00044 bool ResetEvent (); 00045 bool IsSignaled (); 00046 bool WaitForEvent( unsigned long time = ULONG_MAX ); 00047 }; 00048 00051 // 00052 // WorkerThread Class Declaration 00053 // 00056 00057 class WorkerThread : public QThread 00058 { 00059 protected: 00060 00061 QMutex m_mutex; 00062 CEvent m_WorkAvailable; 00063 00064 CEvent m_Initialized; 00065 bool m_bInitialized; 00066 00067 ThreadPool *m_pThreadPool; 00068 00069 volatile bool m_bTermRequested; 00070 QString m_sName; 00071 00072 long m_nIdleTimeoutMS; 00073 bool m_bAllowTimeout; 00074 00075 00076 protected: 00077 00078 virtual void run(); 00079 virtual void ProcessWork() = 0; 00080 00081 00082 public: 00083 00084 WorkerThread( ThreadPool *pThreadPool, const QString &sName ); 00085 virtual ~WorkerThread(); 00086 00087 bool WaitForInitialized( unsigned long msecs ); 00088 void SignalWork (); 00089 void SetTimeout ( long nIdleTimeout ); 00090 00091 }; 00092 00095 // 00096 // CThreadPool Class Declaration 00097 // 00100 00101 typedef QPtrList< WorkerThread > WorkerThreadList; 00102 00103 class ThreadPool 00104 { 00105 friend class WorkerThread; 00106 00107 protected: 00108 00109 QString m_sName; 00110 00111 QMutex m_mList; 00112 00113 QWaitCondition m_threadAvail; 00114 00115 WorkerThreadList m_lstThreads; 00116 WorkerThreadList m_lstAvailableThreads; 00117 00118 int m_nInitialThreadCount; 00119 int m_nMaxThreadCount; 00120 long m_nIdleTimeout; 00121 00122 protected: 00123 00124 void InitializeThreads(); 00125 00126 WorkerThread *AddWorkerThread ( bool bMakeAvailable, long nTimeout ); 00127 00128 void ThreadAvailable ( WorkerThread *pThread ); 00129 void ThreadTerminating( WorkerThread *pThread ); 00130 00131 virtual WorkerThread *CreateWorkerThread( ThreadPool *, const QString &sName ) = 0; 00132 00133 public: 00134 00135 ThreadPool( const QString &sName ); 00136 virtual ~ThreadPool( ); 00137 00138 WorkerThread *GetWorkerThread(); 00139 00140 }; 00141 00142 00143 #endif
1.5.5