00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #ifndef IXE_ThreadPool_H
00025 #define IXE_ThreadPool_H
00026
00027
00028 #include "platform.h"
00029
00030
00031 #include <queue>
00032 #include <set>
00033
00034
00035 #include "include/ixe.h"
00036 #include "Common/Lock.h"
00037
00038 namespace IXE {
00039
00040 #ifdef _WIN32
00041
00042 #define TRESULT unsigned int __stdcall
00043
00044 #else // !_WIN32
00045
00046 #define TRESULT void*
00047
00048 extern pthread_key_t jmpbuf_key;
00049 #endif // _WIN32
00050
00052
00053 extern "C" TRESULT ThreadMain(void*);
00054
00080 class ThreadPool
00081 {
00082 public:
00083
00095 class Thread {
00096
00097 public:
00098 union TaskDescr {
00099
00100
00101
00102
00103
00104
00105 TaskDescr(long a) : i(a) { }
00106 TaskDescr(void* a) : p(a) { }
00107 long i;
00108 void* p;
00109 };
00110
00114 void Start();
00115
00116 protected:
00117 Thread(ThreadPool&);
00118 virtual ~Thread();
00119
00123 virtual Thread* clone(ThreadPool&) const = 0;
00124
00128 virtual void Run(TaskDescr) = 0;
00129
00133 static TRESULT Main(void*);
00137 static void Destroy(void *p);
00138
00139 Thread(Thread const&);
00140 Thread& operator =(Thread const&);
00141
00142 # ifdef _WIN32
00143 HANDLE thread;
00144 # else
00145 pthread_t thread;
00146 # endif
00147 ThreadPool& pool;
00148 bool destroying;
00149
00150 friend class ThreadPool;
00151 };
00152
00154
00155
00156 ThreadPool(char const* process_name,
00157 int min_threads, int max_threads,
00158 int timeout);
00159
00173 ThreadPool(char const* process_name,
00174 Thread const* prototype,
00175 int min_threads, int max_threads,
00176 int timeout);
00177
00178 ~ThreadPool();
00179
00181
00182
00183 void AddTask(Thread::TaskDescr);
00184
00185 void init(Thread const* prototype);
00186
00187 private:
00188
00189 typedef std::set<Thread*> ThreadSet;
00190 typedef std::queue<Thread::TaskDescr> TaskQueue;
00191
00192 Locked<ThreadSet> threads;
00193 Locked<TaskQueue> tasks;
00194
00195 Count const minThreads, maxThreads;
00196 Locked<Count> busyThreads;
00197 Locked<bool> destructing;
00198
00199 Condition idle_thread;
00200 Condition task_available;
00201
00202 int const timeout;
00203 char const* process_name;
00204
00205 friend class Thread;
00206
00207 public:
00208 void Run(int socket_port, int socket_queue_size,
00209 unsigned socket_timeout);
00210 };
00211
00212 }
00213
00214 #endif