Thread.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #ifndef ADCHPP_THREAD_H
00020 #define ADCHPP_THREAD_H
00021
00022 #ifndef _WIN32
00023 # include <pthread.h>
00024 # include <sched.h>
00025 # include <sys/resource.h>
00026 #endif
00027
00028 #include "Exception.h"
00029
00030 namespace adchpp {
00031
00032 STANDARD_EXCEPTION(ThreadException);
00033
00034 class Thread : private boost::noncopyable
00035 {
00036 public:
00037
00038 ADCHPP_DLL void start() throw(ThreadException);
00039 ADCHPP_DLL void join() throw();
00040
00041 #ifdef _WIN32
00042 enum Priority {
00043 LOW = THREAD_PRIORITY_BELOW_NORMAL,
00044 NORMAL = THREAD_PRIORITY_NORMAL,
00045 HIGH = THREAD_PRIORITY_ABOVE_NORMAL
00046 };
00047
00048 Thread() throw() : threadHandle(INVALID_HANDLE_VALUE) { }
00049 virtual ~Thread() {
00050 if(threadHandle != INVALID_HANDLE_VALUE)
00051 CloseHandle(threadHandle);
00052 }
00053
00054 void setThreadPriority(Priority p) throw() { ::SetThreadPriority(threadHandle, p); }
00055
00056 bool isRunning() throw() { return (threadHandle != INVALID_HANDLE_VALUE); }
00057
00058 static void sleep(uint32_t millis) { ::Sleep(millis); }
00059 static void yield() { ::Sleep(1); }
00060
00061 #elif defined(HAVE_PTHREAD)
00062
00063 enum Priority {
00064 LOW = 1,
00065 NORMAL = 0,
00066 HIGH = -1
00067 };
00068 Thread() throw() : t(0) { }
00069 virtual ~Thread() {
00070 if(t != 0) {
00071 pthread_detach(t);
00072 }
00073 }
00074
00075 void setThreadPriority(Priority p) { setpriority(PRIO_PROCESS, 0, p); }
00076 bool isRunning() { return (t != 0); }
00077
00078 static void sleep(uint32_t millis) { ::usleep(millis*1000); }
00079 static void yield() { ::sched_yield(); }
00080
00081 #else
00082 #error No threading support found
00083 #endif
00084
00085 protected:
00086 virtual int run() = 0;
00087
00088 #ifdef _WIN32
00089 HANDLE threadHandle;
00090 static DWORD WINAPI starter(void* p) {
00091 Thread* t = (Thread*)p;
00092 return (DWORD)t->run();
00093 }
00094 #else
00095 pthread_t t;
00096 static void* starter(void* p) {
00097 Thread* t = (Thread*)p;
00098 return (void*)t->run();
00099 }
00100 #endif
00101 };
00102
00103 }
00104
00105 #endif // THREAD_H